[quote]
此代码处理,对数据插入不成功时做的处理!
[/quote]
此代码处理,对数据插入不成功时做的处理!
[/quote]
package com.my.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestTransaction {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/student?user=root&password=root");
stmt = conn.createStatement();
conn.setAutoCommit(false);
stmt.addBatch("insert into c values(20, 'c15')");
stmt.addBatch("insert into c values(21, 'c16')");
stmt.addBatch("insert into c values(22, 'c17')");
stmt.executeBatch();
conn.commit();
conn.setAutoCommit(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
try {
if(null != conn) {
conn.rollback();
conn.setAutoCommit(true);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
try {
if(null != conn) {
conn.close();
conn = null;
}
if(null != stmt) {
stmt.close();
stmt = null;
}
} catch(SQLException e) {
e.printStackTrace();
}
}
}
}