在最近做JDBC事务练习的一个案例中,出现一个疑问,请大佬们看看
案例很简单:张三丰给灭绝师太转账5000
①:张三账户-5000
②:灭绝师太账户+5000
表初始数据如下
以下是我的代码和工具类
工具类:
public class JDBCUTILs {
static String user;
static String password;
static String url;
static String driver;
static {
try {
Properties pre = new Properties();
pre.load(new FileInputStream("src\\JDBC.properties"));
user = pre.getProperty("user");
password = pre.getProperty("password");
driver = pre.getProperty("driver");
url = pre.getProperty("url");
Class.forName(driver);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/*
* 功能一:获取连接
* 获取可用的连接对象
* */
public static Connection getConnection(){
try {
return DriverManager.getConnection(url,user,password);
} catch (Exception throwables) {
throw new RuntimeException(throwables);
}
}
/*
* 功能:释放资源
* */
public static void close(ResultSet set, Statement statement,Connection connection) {
try {
if (set != null){
set.close();
}
if (statement!=null){
statement.close();
}
if (connection!=null){
connection.close();
}
} catch (Exception throwables) {
throw new RuntimeException(throwables);
}
}
}
@Test
public void TestUSETrancation() {
Connection connection = null;
PreparedStatement psm = null;
try {
connection = JDBCUTILs.getConnection();
connection.setAutoCommit(false);
psm = connection.prepareStatement("update account set balance = ? where stuname = ?");
psm.setDouble(1,5000);
psm.setString(1,"张三丰");
psm.executeUpdate();
psm.setDouble(1,15000);
psm.setString(2,"灭绝师太");
psm.executeUpdate();
connection.commit();
System.out.println("修改成功");
} catch (Exception throwables) {
try {
connection.rollback();
} catch (Exception e) {
e.printStackTrace();
}
}finally {
try {
JDBCUTILs.close(null,psm,connection);
} catch (Exception throwables) {
throwables.printStackTrace();
}
}
}
}
执行完毕后控制台输出"修改成功"。说明执行了commit提交数据,但是数据库中的表并没有更新数据
这让我百思不得其解,后来我将sql语句中where后的查询条件setname改为了setid,再次执行后就修改成功了。
stuid和stuname的区别是我将stuid设置为了主键,
所以在想数据库修改数据不成功到底和主键有什么关系。请知道的大佬解答,谢谢。