目录
前言
JDBC更新数据库表,加和减相同保证数据不丢失,使用事务。
一、数据库表
a1 加某个数,a2减相同的数,保证数据总数不变
二、代码如下
package Test01;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 测试jdbc执行事务
* @author 葫芦鸡
*
*/
public class TestTransaction {
public static void main(String[] args) {
Connection con =null;
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "0705");
} catch (SQLException e) {
e.printStackTrace();
}
try {
con.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
String sql1 = "update student set a1=(a1+10) where id=?";
String sql2 = "update students set a2=(a2-10) where id=?";//没有students表所以会执行失败
try {
ps1 = con.prepareStatement(sql1);
} catch (SQLException e) {
e.printStackTrace();
}
try {
ps2 = con.prepareStatement(sql2);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
//执行事务
ps1.setInt(1, 1);
ps1.executeUpdate();
System.out.println("------------------1");
ps2.setInt(1, 2);
ps2.executeUpdate();
System.out.println("------------------2");
con.commit();
System.out.println("------------------3");
}catch(Exception e) {
//回滚
try {
System.out.println("------------------4");
con.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}finally{
System.out.println("------------------5");
try {
ps1.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ps2.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
con.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
总结
设置手动提交,用try catch实现,try里放事务代码并手动提交,catch里设置回滚,当事务报错执行回滚。
mysql数据库表的存储引擎只能是INNODB