JDBC Batch的使用

   检测数据库是否支持batch

   DatabaseMetaData.supportsBatchUpdates()

 

   然后就是三个比较有用的方法:

 

   addBatch: 将Statement, PreparedStatement, and CallableStatement添加进batch里面

   

   executeBatch: 返回各个语句的执行结果

   

   clearBatch: 将batch里面的sql语句清除掉

 

   在这个里面有一个值得注意的是要设置connection的事务提交类型

 

   setAutoCommit(false)为手动提交

 

 // Create statement object
	Statement stmt = conn.createStatement();

	// Set auto-commit to false
	conn.setAutoCommit(false);

	// Create SQL statement
	String SQL = "INSERT INTO Employees (id, first, last, age) " +
				 "VALUES(200,'Zia', 'Ali', 30)";
	// Add above SQL statement in the batch.
	stmt.addBatch(SQL);

	// Create one more SQL statement
	String SQL = "INSERT INTO Employees (id, first, last, age) " +
				 "VALUES(201,'Raj', 'Kumar', 35)";
	// Add above SQL statement in the batch.
	stmt.addBatch(SQL);

	// Create one more SQL statement
	String SQL = "UPDATE Employees SET age = 35 " +
				 "WHERE id = 100";
	// Add above SQL statement in the batch.
	stmt.addBatch(SQL);

	// Create an int[] to hold returned values
	int[] count = stmt.executeBatch();

	//Explicitly commit statements to apply changes
	conn.commit();
 

你可能感兴趣的:(sql,jdbc)