stmt=conn.createStatement(); stmt=conn.createStatement();
stmt.addBatch("insert into test(name,age,score) values('haha',10,33)");
stmt.executeBatch(); //批量执行SQL语句
conn.commit(); //提交事物
conn.setAutoCommit(true);
4.源码实战
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC_Transaction {
/*MySQL数据库编程
* 实例(7):JDBC批量处理事物Transaction*/
public static void main(String[] args) {
//0.连接数据库相关参数
String url="jdbc:mysql://localhost:3306/jdbc_test_db"; //数据库URL(资源定位唯一标识符)
String DBusername="root"; //数据库用户名
String DBpasswd="896013"; //数据库密码
//1.加载数据库驱动,将Driver注册到DriverManager中
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
//2.通过数据库URL连接到数据库
Connection conn=null;
Statement stmt=null;
try{
//3.获得表示连接到数据库的Connection对象
conn=DriverManager.getConnection(url, DBusername, DBpasswd);
//4.设置SQL语句不自动执行
conn.setAutoCommit(false);
//5.获取Statement对象
stmt=conn.createStatement();
stmt.addBatch("insert into test(name,age,score) values('haha',10,33)");
stmt.addBatch("insert into test(name,age,score) values('heihei',11,44)");
stmt.addBatch("insert into test(name,age,score) values('xixi',14,55)");
stmt.executeBatch(); //批量执行SQL语句
conn.commit(); //提交事物
conn.setAutoCommit(true);
}catch(SQLException e){
e.printStackTrace();
}
//5.释放JDBC资源
if(stmt!=null) //关闭声明
{
try{
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
if(conn!=null) //关闭连接
{
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
} ?
运行结果:
(1)注释事物提交语句 //conn.commit(); // conn.setAutoCommit(true);
(2)执行conn.commit()结果