简体   繁体   English

Java JDBC返回错误的生成键

[英]Java JDBC Return wrong generated keys

I am trying to get an ID of a newly inserted row from my database. 我正在尝试从数据库中获取新插入的行的ID。 After debugging and following the code step by step but it always returns a "0" value. 在调试并逐步执行代码后,但始终返回“ 0”值。

HashMap<String, String> response = new HashMap<String, String>();
    Integer generatedId = 0;
    try {
        ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        ps.executeUpdate();
        rs = ps.getGeneratedKeys();
        rs.next();
        if (rs.isBeforeFirst()) {
            generatedId = rs.getInt(1);
        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
        response.put("STATUS", "ERROR");
    }

The code sits in a static method called update which accepts a string with SQL query String. 代码位于称为update的静态方法中,该方法接受带有SQL查询String的字符串。

public static HashMap<String, String> update(String query)

Your code makes no sense. 您的代码没有任何意义。

If you call rs.next() , as you should, rs.isBeforeFirst() cannot possibly be true, and the following rs.getInt() would fail if it was. 如果按您的方式调用rs.next() ,则rs.isBeforeFirst()可能无法为true,并且以下rs.getInt()可能会失败。

Remove the test. 删除测试。 It should really be if (rs.next()) etc. 确实应该是if (rs.next())等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM