您的位置:首页 > 其它

JDBC简单的处理事务和批处理

2010-05-15 00:14 316 查看
JDBC处理事务:

package SecondStep;

import java.sql.*;

/**
*
* 处理事务transaction 同时执行了批处理 addBatch 和
*
*/
public class GeDemo6 {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;

try {
Class.forName("com.mysql.jdbc.Driver");

String url = "jdbc:mysql://localhost:3306/test";

String user = "root";

String password = "123";

connection = DriverManager.getConnection(url, user, password);

// 禁用自动提交模式
connection.setAutoCommit(false);

statement = connection.createStatement();

// 执行这两条SQL语句 如果 其中一条出现错误 那么进入异常处理 回滚事务
statement
.addBatch("insert into testtable(username,password) values('admindemo7','123456')");
statement
.addBatch("insert into testtable(username,password) values('admindemo6','456456')");

// 将一批命令提交给数据库来执行,如果全部命令执行成功,则返回更新计数组成的数组
statement.executeBatch();

// 手动提交事务
connection.commit();

// 事务提交成功   启用自动提交模式
connection.setAutoCommit(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
// 异常处理 回滚事务
try {
if (connection != null) {
// 回滚事务
connection.rollback();
// 启用自动提交模式
connection.setAutoCommit(true);
}
} catch (SQLException el2) {
el2.printStackTrace();
} catch (Exception el3) {
el3.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: