preparedStatement.executeUpdate() 未返回大于 0 的值

问题描述 投票:0回答:1

当我在表单中插入数据并提交时,没有返回错误,但是当我检查数据库时,我发现之前的相同信息保持不变,没有任何变化,并且弹出消息“没有更新用户”在控制台上。

我尝试检查我的数据库字段和 servlet,但仍然找不到问题。 这是我修改表单时发生的情况:

(ID 7 NOM doe PRENOM jhon 年龄 25 密码 jhon123 电子邮件 [email protected] IDROLE 2 用户更新成功!)

请问问题出在哪里?

这是 DAO :

 private static final String Update_user = "UPDATE utilisateur SET 
 idutilisateur = ? ,nom = ? ,prenom=?  , age = ?,email = ? , mot_de_pass = ? , idrole = ?"
            + " WHERE  idutilisateur = ?";
    `public static void updateUser(Utilisateurs u) throws SQLException {
        try (Connection connection = Conx();
             PreparedStatement preparedStatement = connection.prepareStatement(Update_user)) {

            preparedStatement.setInt(1, u.getIdUtilisateurs());
            preparedStatement.setString(2, u.getNom());
            preparedStatement.setString(3, u.getPrenom());
            preparedStatement.setInt(4, u.getAge());
            preparedStatement.setString(5, u.getEmail());
            preparedStatement.setString(6, u.getPassword());
            preparedStatement.setInt(7, u.getRole().getIdRole());
            preparedStatement.setInt(8, u.getIdUtilisateurs());

            int rowsUpdated = preparedStatement.executeUpdate();

            if (rowsUpdated > 0) {
                connection.commit(); 
                System.out.println("User updated successfully!");
            } else {
                System.out.println("No user was updated.");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
java jdbc
1个回答
0
投票

您在问题中没有发布足够的信息供我们做出诊断。但我可以给你一些提示和一些示例代码。

两个关键提示:

  • 您应该始终将数据库代码与 UI 分开编写和测试。
  • 从小事做起,一步一步来,一次添加一点代码,边做边编译和测试。

这里是一些使用 H2 数据库引擎的示例代码。

默认情况下,H2 连接处于“自动提交”模式。所以我们的UPDATE立即生效。请参阅 H2 中的

SET AUTOCOMMIT
 命令。
package work.basil.example.db; import org.h2.jdbcx.JdbcDataSource; import javax.sql.DataSource; import java.sql.*; import java.time.Instant; import java.util.Collection; import java.util.List; public class FrenchUsers { public static void main ( String[] args ) { FrenchUsers app = new FrenchUsers ( ); app.demo ( ); } private void demo ( ) { final DataSource dataSource = this.obtainDataSource ( ); this.prepareDatabase ( dataSource ); this.populateDatabase ( dataSource , this.sampleData ( ) ); this.dumpToConsole ( dataSource ); this.modifyOneRowByRoleCode ( dataSource ); this.dumpToConsole ( dataSource ); } private DataSource obtainDataSource ( ) { org.h2.jdbcx.JdbcDataSource ds = new JdbcDataSource ( ); // An implementation of `javax.sql.DataSource` bundled with H2. ds.setURL ( "jdbc:h2:mem:ex_french_users_db;DB_CLOSE_DELAY=-1" ); ds.setUser ( "scott" ); ds.setPassword ( "tiger" ); ds.setDescription ( "An example database showing how to modify a row per changes to an object." ); return ds; } private void prepareDatabase ( DataSource dataSource ) { System.out.println ( "INFO - Running `prepareDatabase` method. " + Instant.now ( ) ); String sql = """ CREATE TABLE IF NOT EXISTS utilisateur_ ( id_ INTEGER NOT NULL , nom_ TEXT NOT NULL , prenom_ TEXT NOT NULL , age_ INTEGER NOT NULL , email_ TEXT NOT NULL , mot_de_passe_ TEXT NOT NULL , role_code_ INTEGER NOT NULL , CONSTRAINT id_ PRIMARY KEY ( id_ ) ) ; """; try ( Connection conn = dataSource.getConnection ( ) ; Statement stmt = conn.createStatement ( ) ; ) { stmt.executeUpdate ( sql ); } catch ( SQLException e ) { e.printStackTrace ( ); } } private Collection < Utilisateur > sampleData ( ) { System.out.println ( "INFO - Running `sampleData` method. " + Instant.now ( ) ); return List.of ( new Utilisateur ( 11 , "Abadie" , "Alice" , 49 , "[email protected]" , "123" , 7 ) , new Utilisateur ( 12 , "Beaulieu" , "Bob" , 22 , "[email protected]" , "letmein" , 42 ) , new Utilisateur ( 13 , "Charbonnier" , "Carol" , 72 , "[email protected]" , "password" , 7 ) ); } private void populateDatabase ( final DataSource dataSource , final Collection < Utilisateur > originalData ) { System.out.println ( "INFO - Running `populateDatabase` method. " + Instant.now ( ) ); String sql = """ INSERT INTO utilisateur_ ( id_ , nom_ , prenom_ , age_ , email_ , mot_de_passe_ ,role_code_ ) VALUES ( ? , ? , ? , ? , ? , ? , ? ) ; """; try ( Connection conn = dataSource.getConnection ( ) ; PreparedStatement preparedStatement = conn.prepareStatement ( sql ) ; ) { for ( Utilisateur utilisateur : originalData ) { preparedStatement.setInt ( 1 , utilisateur.id ( ) ); preparedStatement.setString ( 2 , utilisateur.nom ( ) ); preparedStatement.setString ( 3 , utilisateur.prenom ( ) ); preparedStatement.setInt ( 4 , utilisateur.age ( ) ); preparedStatement.setString ( 5 , utilisateur.email ( ) ); preparedStatement.setString ( 6 , utilisateur.motDePasse ( ) ); preparedStatement.setInt ( 7 , utilisateur.roleCode ( ) ); preparedStatement.executeUpdate ( ); } } catch ( SQLException e ) { e.printStackTrace ( ); } } private void modifyOneRowByRoleCode ( final DataSource dataSource ) { System.out.println ( "INFO - Running `modifyOneRowByRoleCode` method. " + Instant.now ( ) ); Utilisateur utilisateur = this.modifiedUtilisateur ( ); String sql = """ UPDATE utilisateur_ SET role_code_ = ? WHERE id_ = ? ; """; try ( Connection conn = dataSource.getConnection ( ) ; PreparedStatement preparedStatement = conn.prepareStatement ( sql ) ; ) { preparedStatement.setInt ( 1 , utilisateur.roleCode ( ) ); preparedStatement.setInt ( 2 , utilisateur.id ( ) ); int countRowsAffected = preparedStatement.executeUpdate ( ); System.out.println ( "DEBUG - SQL UPDATE affected " + countRowsAffected + " rows." ); } catch ( SQLException e ) { e.printStackTrace ( ); } } private Utilisateur modifiedUtilisateur ( ) { System.out.println ( "INFO - Running `modifiedUtilisateur` method. " + Instant.now ( ) ); Utilisateur vieux = List.copyOf ( this.sampleData ( ) ).get ( 2 ); Utilisateur nouveau = new Utilisateur ( vieux.id ( ) , vieux.nom ( ) , vieux.prenom ( ) , vieux.age ( ) , vieux.email ( ) , vieux.motDePasse ( ) , vieux.roleCode ( ) + ( 99 - vieux.roleCode ( ) ) // Changing the role code number to 99, to update a row in the database. ); System.out.println ( "vieux = " + vieux ); System.out.println ( "nouveau = " + nouveau ); System.out.println ( vieux.equals ( nouveau ) ); return nouveau; } private void dumpToConsole ( final DataSource dataSource ) { System.out.println ( "INFO - Running `dumpToConsole` method. " + Instant.now ( ) ); String sql = """ SELECT * FROM utilisateur_ ; """; try ( Connection conn = dataSource.getConnection ( ) ; PreparedStatement preparedStatement = conn.prepareStatement ( sql ) ; ) { try ( ResultSet resultSet = preparedStatement.executeQuery ( ) ) { while ( resultSet.next ( ) ) { // We expect a single row in each result set, for the count. int id = resultSet.getInt ( 1 ); String nom = resultSet.getString ( 2 ); String prenom = resultSet.getString ( 3 ); int age = resultSet.getInt ( 4 ); String email = resultSet.getString ( 5 ); String motDePasse = resultSet.getString ( 6 ); int roleCode = resultSet.getInt ( 7 ); String line = String.join ( " | " , Integer.toString ( id ) , nom , prenom , Integer.toString ( age ) , email , motDePasse , Integer.toString ( roleCode ) ); System.out.println ( "line = " + line ); } } } catch ( SQLException e ) { throw new RuntimeException ( e ); } } } record Utilisateur( int id , String nom , String prenom , int age , String email , String motDePasse , // Of course we would *NEVER* actually store a password, not in real work. int roleCode ) {}

运行时,我们看到 Carol 将她的角色代码更改为 99。

INFO - Running `prepareDatabase` method. 2023-09-04T01:09:51.759704Z INFO - Running `sampleData` method. 2023-09-04T01:09:51.918480Z INFO - Running `populateDatabase` method. 2023-09-04T01:09:51.918820Z INFO - Running `dumpToConsole` method. 2023-09-04T01:09:51.921699Z line = 11 | Abadie | Alice | 49 | [email protected] | 123 | 7 line = 12 | Beaulieu | Bob | 22 | [email protected] | letmein | 42 line = 13 | Charbonnier | Carol | 72 | [email protected] | password | 7 INFO - Running `modifyOneRowByRoleCode` method. 2023-09-04T01:09:51.929767Z INFO - Running `modifiedUtilisateur` method. 2023-09-04T01:09:51.929831Z INFO - Running `sampleData` method. 2023-09-04T01:09:51.929869Z vieux = Utilisateur[id=13, nom=Charbonnier, prenom=Carol, age=72, [email protected], motDePasse=password, roleCode=7] nouveau = Utilisateur[id=13, nom=Charbonnier, prenom=Carol, age=72, [email protected], motDePasse=password, roleCode=99] false DEBUG - SQL UPDATE affected 1 rows. INFO - Running `dumpToConsole` method. 2023-09-04T01:09:51.954863Z line = 11 | Abadie | Alice | 49 | [email protected] | 123 | 7 line = 12 | Beaulieu | Bob | 22 | [email protected] | letmein | 42 line = 13 | Charbonnier | Carol | 72 | [email protected] | password | 99

© www.soinside.com 2019 - 2024. All rights reserved.