使用JDBC的事务操作
package com.mldn;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
public class Transaction
{
// 数据库驱动:
public static final String DBDRIVER = “com.mysql.jdbc.Driver”;
// 数据库url:
public static final String DBURL = “jdbc:mysql://localhost:3306/school?characterEncoding=utf8”;
// 数据库用户名:
public static final String DBUSER = “root”;
// 连接密码:
public static final String DBPASS = “123456”;
public static void main(String[] args)
{
// 声明数据库连接:
Connection conn = null;
// 声明处理语句:
Statement stmt = null;
// 加载驱动:
try
{
Class.forName(DBDRIVER);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
// 获取数据库连接:
try
{
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
}
catch (SQLException e)
{
e.printStackTrace();
}
// 取消连接自动提交:
try
{
conn.setAutoCommit(false);
}
catch (SQLException e)
{
e.printStackTrace();
}
// 获取处理语句:
try
{
stmt = conn.createStatement();
}
catch (SQLException e)
{
e.printStackTrace();
}
// 添加批处理
try
{
stmt.addBatch(“insert into student(name, age, sex, birthday) values(‘张三’, 26, ‘男’, ‘1989-07-22’)”);
stmt.addBatch(“insert into student(name, age, sex, birthday) values(‘王三’, 24, ‘女’, ‘1986-08-02’)”);
stmt.addBatch(“insert into student(name, age, sex, birthday) values(‘李三’, 23, ‘男’, ‘1982-01-22’)”);
stmt.addBatch(“insert into student(name, age, sex, birthday) values(‘赵三’, 25, ‘女’, ‘1991-11-22’)”);
// 将‘sex’字段变为:sexs;
stmt.addBatch(“insert into student(name, age, sexs, birthday) values(‘杨三’, 22, ‘男’, ‘1989-11-05’)”);
stmt.addBatch(“insert into student(name, age, sex, birthday) values(‘孔三’, 21, ‘女’, ‘1971-10-14’)”);
}
catch (SQLException e)
{
e.printStackTrace();
}
// 事务处理:
try
{ // 执行批处理
int[] status = stmt.executeBatch();
System.out.println(“插入成功,影响了” + status.length + “行”);
// 事务操作无误,提交事务!
conn.commit();
}
catch (Exception e)
{
try
{ // 事务回滚到未插入状态
conn.rollback();
System.out.println(“操作失败,事务回滚完毕!”);
}
catch (SQLException el)
{
el.printStackTrace();
}
}
// 关闭操作
try
{
stmt.close();
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
/*
ubuntu@xu-desktop:~$ java com.mldn.Transaction
插入成功,影响了6行
ubuntu@xu-desktop:~$ java com.mldn.Transaction
操作失败,事务回滚完毕!
*/
声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《使用JDBC的事务操作》
本文地址:http://www.xiupu.net/archives-165.html
关注公众号:
微信赞赏
支付宝赞赏