源码模板参考:
//事务操作
public static void shiwu() {
//加载javaMysql驱动程序
try {
Class.forName("JDBCDome.JDBCDome");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//通过用户名和密码连接数据库
String url="jdbc:mysql://localhost:3306/box2";
String user="root";
String password="";
//通过用户名和密码连接数据库,返回连接对象(该返回对象表示数据库连接成功)
java.sql.Connection conn = null;
try {
conn = DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sql1="sql语句1";
String sql2="sql语句2";
String sql3="sql语句3";
try {
//设置手动提交事务(取消自动提交)
conn.setAutoCommit(false);
PreparedStatement ps=conn.prepareStatement(sql1);
ps.executeUpdate();
ps.setInt(parameterIndex, x);
ps=conn.prepareStatement(sql1);
ps.executeUpdate();
ps.setInt(parameterIndex, x);
ps=conn.prepareStatement(sql1);
ps.executeUpdate();
ps.setInt(parameterIndex, x);
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
PreparedStatement ps=conn.prepareStatement(sql1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}