package java_web;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class JdbcTxDemo {
public final static String URL="jdbc:mysql://localhost:3306/test";
public final static String USERNAME="root";
public final static String PASSWORD="";
public final static String DRIVER="com.mysql.jdbc.Driver";
public static Connection conn =null;
public static void txTest(){
try {
Class.forName(DRIVER);
conn=(Connection) DriverManager.getConnection(URL,USERNAME,PASSWORD);
conn.setAutoCommit(false);
String sql1 = "insert test(name,sex)values('123a',1)";
String sql2 = "insert test(name,sex)values('1234b',1)";
String sql3 = "insert test(name,sex)values('1238',1)";
PreparedStatement ps=(PreparedStatement) conn.prepareStatement(sql1);
ps.addBatch(sql1);
ps.addBatch(sql2);
ps.addBatch(sql3);//加入批处理
ps.executeBatch();//执行批处理
conn.commit();
ps.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
txTest();
}
}
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class JdbcTxDemo {
public final static String URL="jdbc:mysql://localhost:3306/test";
public final static String USERNAME="root";
public final static String PASSWORD="";
public final static String DRIVER="com.mysql.jdbc.Driver";
public static Connection conn =null;
public static void txTest(){
try {
Class.forName(DRIVER);
conn=(Connection) DriverManager.getConnection(URL,USERNAME,PASSWORD);
conn.setAutoCommit(false);
String sql1 = "insert test(name,sex)values('123a',1)";
String sql2 = "insert test(name,sex)values('1234b',1)";
String sql3 = "insert test(name,sex)values('1238',1)";
PreparedStatement ps=(PreparedStatement) conn.prepareStatement(sql1);
ps.addBatch(sql1);
ps.addBatch(sql2);
ps.addBatch(sql3);//加入批处理
ps.executeBatch();//执行批处理
conn.commit();
ps.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
txTest();
}
}