jdbc中的事务管理
package com.chenhuan.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class jdbcTransaction {
public static String url = "jdbc:mysql://localhost/pro?Unicode=true&characterEncoding=gb2312";
public static String driver = "com.mysql.jdbc.Driver";
public static String username = "root";
public static String password = "123";
public static Statement stmt;
public static Connection conn;
public static void main(String args[]){
System.out.println(dbConnect());
try {
conn.setAutoCommit(false);
stmt.executeUpdate("insert into admin values('7','ch','ch','ch','ch','ch')");
stmt.executeUpdate("insert into admin values('ch','ch','ch','ch','ch')");
conn.commit();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void dbConnect(){
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
System.out.println("conn="+conn);
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
}
@说明:
jdbc中的事务是通过conn的提交事务进行管理的,如果捕获到异常则不会进行事务提交,达到操作和数据的一致性。