package denglianbin.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/*
* 重要三行代码“
* conn.setAutoCommit(false);
* conn.commit();
* conn.rollback();
* */
public class JDBCTest06 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//建立连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dlb_mysql", "root", "123456");
conn.setAutoCommit(false);
//获取预编译的操作对象
String sql = "update t_act set balance = ? where actno = ?";
ps = conn.prepareStatement(sql);
//给?传值
ps.setDouble(1,10000);
ps.setInt(2,111);
int count = ps.executeUpdate();
//再给?传值
ps.setDouble(1,10000);
ps.setInt(2,222);
count += ps.executeUpdate();
System.out.println(count ==2 ? "转账成功" : "转账失败");
conn.commit();
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
} finally {
if(ps != null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}