1.事务的特性
- 原子性
- 一致性
- 隔离性
- 持久性
2.JDBC事务控制
Connection对象有三个函数对事务控制
- 开启事务 con.setAutoCommit(false);
- 提交事务 con.commit();
- 回滚事务 con.rollback();
3.代码实例
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class sql{
/**
* @param args
*/
//驱动程序就是之前在classpath中配置的JDBC的驱动程序的JAR 包中
public static final String DBDRIVER = "com.mysql.jdbc.Driver";
//连接地址是由各个数据库生产商单独提供的,所以需要单独记住
public static final String DBURL = "jdbc:mysql://192.168.0.31:3306/myDB";
//连接数据库的用户名
public static final String DBUSER = "root";
//连接数据库的密码
public static final String DBPASS = "";
public static void Account(String fromName, String toName) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
conn.setAutoCommit(false);
stmt = conn.prepareStatement("update user set account =? where name=?");
stmt.setInt(1, 0);
stmt.setString(2, fromName);
stmt.execute();
stmt.setInt(1, 100);
stmt.setString(2, toName);
stmt.execute();
conn.commit();
} catch (SQLException e) {
if (conn != null)
{
try {
conn.rollback();
} catch (SQLException el) {
el.printStackTrace();
}
}
}
finally {
try {
if (conn != null) conn.close();
if (stmt != null) stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Class.forName(DBDRIVER);
Account("Harris", "April");
}
}
执行前
mysql> select * from user;
+--------+---------+
| name | account |
+--------+---------+
| Harris | 100 |
| April | 0 |
+--------+---------+
2 rows in set (0.00 sec)
执行后
mysql> select * from user;
+--------+---------+
| name | account |
+--------+---------+
| Harris | 0 |
| April | 100 |
+--------+---------+
2 rows in set (0.00 sec)