【发布时间】:2022-06-13 21:31:57
【问题描述】:
我在 java 程序中使用的数据库更新方法不会更新数据库。只有当我在同一个类中运行 read 方法时,它才会显示数据库的更新版本,但实际上并不更新数据库。 我所做的是在我的主类中运行 unit_elimination(2) 方法,然后它不更新数据库(它应该将 main_table 中 ID=1 的行的状态列变为 2,但它在数据库)。然后我使用 showname 方法读取表,它显示了更新的数字,但数据库实际上并没有更新。
package com.company;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.*;
public class Stdn implements AutoCloseable{
private Connection connection;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
public Stdn() throws SQLException {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:1522/juni_project" , "root", "password");
connection.setAutoCommit(false);
}
public void showName(String A , String B) throws SQLException{
preparedStatement = connection.prepareStatement("select "+ A + " from " + B + ";" );
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getString(1));
}
}
public void update(String A , String B , int C , int D) {
try{
PreparedStatement preparedStatement = connection.prepareStatement("UPDATE "+ A + " SET " + B + " =? WHERE ID = ? ;");
preparedStatement.setInt(1,C);
preparedStatement.setInt(2, D);
preparedStatement.executeUpdate();
}
catch (SQLException e){
System.out.println( " Could not update data to the database " + e.getMessage());
}}
public void unit_elimination(int X) throws SQLException {
update("main_table" ,"status", X , 1 );
}
@Override
public void close() throws Exception {
preparedStatement.close();
connection.close();
}}
你能帮我找出问题出在哪里吗?我已经卡在这个问题上几天了,几乎没有空闲时间。
【问题讨论】:
-
可能已阅读事务,是否为数据库连接设置了自动提交?