欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDBC Batch的使用

程序员文章站 2022-05-28 17:49:29
...

   检测数据库是否支持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();
 
相关标签: JDBC SQL