在代码src文件夹下创建文件dbinfo.proparties 内容如下
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc_db
username=root
passwd=zf5732663
事务控制如下:主要是使用rollback函数
package com.zhaofei.jdbc.study;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DButil {
public Connection openConnection() {
Properties prop = new Properties();
String driver = null;
String url = null;
String username = null;
String passwd = null;
try {
prop.load(this.getClass().getClassLoader()
.getResourceAsStream("dbinfo.proparties"));
driver = prop.getProperty("driver");
url = prop.getProperty("url");
username = prop.getProperty("username");
passwd = prop.getProperty("passwd");
Class.forName(driver);// 加载数据库驱动
return DriverManager.getConnection(url, username, passwd);// 返回连接数据库的实例
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void closeConnection(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DButil util = new DButil();
util.add();
}
public void add() {
DButil util = new DButil();
String sql1 = "update AccountTbl set balance = balance - 1000 where name='tom'";
String sql2 = "update AccountTbl set balance = balance + 1000 where name='kite'";
Connection conn = util.openConnection();
try {
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}finally{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}