Java PreparedStatement检索最后插入的ID

时间:2011-04-01 12:11:49

标签: java mysql jdbc prepared-statement

这种方式对这个问题的回答似乎很难在互联网上找到。基本上我使用PreparedStatement将值插入MySQL数据库。我使用PreparedStatement来转义数据以防止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?

3 个答案:

答案 0 :(得分:56)

Statement.RETURN_GENERATED_KEYS中传递prepareStatement()以及您的查询。然后使用PreparedStatement的getGeneratedKeys()来获取包含插入的auto_incremented_id的ResultSet。

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);
                }

答案 1 :(得分:4)

答案 2 :(得分:1)

如果您无法使用RETURN_GENERATED_KEYS,请使用其他语句(此次查询)

SELECT last_insert_id()

确保该表中肯定有一个自动增量主键列。