Java 准备语句检索上次插入的 ID

2022-09-01 04:19:22

以这种方式完成的这个问题的答案似乎很难在互联网上找到。基本上,我使用ReadyStatement将值插入MySQL数据库中。我使用ReadyStatement来转义数据以防止SQL注入攻击。问题是,现在有办法收回这些密钥。

String query="Insert INTO Table_A(name, age) (?, ?)";
//String query="Insert INTO Table_A(name, age) ('abc','123' )";//Doesn't escape
PreparedStatement prest;
prest = con.prepareStatement(query);
prest.setString(1,"abc");
prest.setInt(2,123);
prest.executeUpdate();
//prest.executeUpdate(query, PreparedStatement.RETURN_GENERATED_KEYS); Throws an error
//prest.executeQuery(); Throws an error

那么,如何转义输入并在 Java 中使用 PreparedStatements 呢?


答案 1

与您的查询一起传入。然后使用 getGeneratedKeys() of 获取包含插入auto_incremented_id的结果集。Statement.RETURN_GENERATED_KEYSprepareStatement()PreparedStatement

String query="Insert INTO Table_A(name, age) (?, ?)";
                //String query="Insert INTO Table_A(name, age) ('abc','123' )";//Doesn't escape
                PreparedStatement prest;
                prest = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
                prest.setString(1,"abc");
                prest.setInt(2,123);
                prest.executeUpdate();
                //prest.executeUpdate(query, PreparedStatement.RETURN_GENERATED_KEYS); Throws an error
                //prest.executeQuery(); Throws an error
                ResultSet rs = prest.getGeneratedKeys();
                if(rs.next())
                {
                    int last_inserted_id = rs.getInt(1);
                }

答案 2

推荐