0318

execute() can execute almost any SQL statement, which is troublesome but can be used when the statement type is not clear.
PreparedStatement precompiles SQL: The
execution efficiency is higher than that of statement, which reduces the complexity of variable programming and prevents SQL injection. Where placeholders can only replace ordinary values.
import java.util. *;
import java.io. *;
import java.sql.*;
public class ExecuteSQL
{
	private String driver;
	private String url;
	private String user;
	private String pass;
	public void initParam(String paramFile)throws Exception
	{
		Properties props = new Properties();
		props.load(new FileInputStream(paramFile));
		driver = props.getProperty("driver");
		url = props.getProperty("url");
		user = props.getProperty("user");
		pass = props.getProperty("pass");
	}
	public void executeSql(String sql)throws Exception
	{
		Class.forName(driver);
		try(
			Connection conn = DriverManager.getConnection(url, user , pass);
			Statement stmt = conn.createStatement())
		{
			// Execute SQL, return a boolean value indicating whether it contains a ResultSet
			boolean hasResultSet = stmt.execute(sql);
			// If there is a ResultSet result set after execution, it indicates that it is a query statement
			if (hasResultSet)
			{
				try(
					// get the result set
					ResultSet rs = stmt.getResultSet())
				{
					// ResultSetMetaData is the metadata interface for analyzing the result set
					ResultSetMetaData rsmd = rs.getMetaData();
					int columnCount = rsmd.getColumnCount();
					// Iterate the output ResultSet object
					while (rs.next())
					{
						// print the value of each column in turn
						for (int i = 0 ; i < columnCount ; i++ )
						{
							System.out.print(rs.getString(i + 1) + "\t");
						}
						System.out.print("\n");
					}
				}
			}
			else
			{
				System.out.println("The records affected by this SQL statement are"
					+ stmt.getUpdateCount() + "条");
			}
		}
	}
	public static void main(String[] args) throws Exception
	{
		ExecuteSQL es = new ExecuteSQL();
		es.initParam("mysql.ini");
		System.out.println("------Execute the DDL statement to delete the table-----");
		es.executeSql("drop table if exists my_test");
		System.out.println("------Execute the DDL statement to build the table-----");
		es.executeSql("create table my_test"
			+ "(test_id int auto_increment primary key, "
			+ "test_name varchar(255))");
		System.out.println("------Execute DML statement to insert data-----");
		es.executeSql("insert into my_test(test_name) "
			+ "select student_name from student_table");
		System.out.println("------Execute the query statement of query data-----");
		es.executeSql("select * from my_test");
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326511755&siteId=291194637