JavaPreparedStatement检索最后插入的ID
以这种方式完成的这个问题的答案似乎很难在互联网上找到。基本上我使用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 呢?
This answer to this question done this way seems to be very difficult to find on the internet. Basically I am inserting values into a MySQL database using PreparedStatement. I use the PreparedStatement to escape the data to prevent SQL Injection attacks. The problem is, there is now way retreving those keys.
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
So how can I escape input and use PreparedStatements in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
prepareStatement()
中的Statement.RETURN_GENERATED_KEYS
与您的查询一起传递。然后使用PreparedStatement的getGenerateKeys()来获取包含插入的auto_incremented_id的ResultSet。pass
Statement.RETURN_GENERATED_KEYS
inprepareStatement()
along with your query. And then use getGeneratedKeys() ofPreparedStatement
to get the ResultSet containing your inserted auto_incremented_id.使用
java.sql.ResultSet java. sql.Statement.getGenerateKeys() 来检索生成的密钥。
Use
java.sql.ResultSet java.sql.Statement.getGeneratedKeys() to retrieve your generated keys.
如果您无法使用
RETURN_GENERATED_KEYS
,请使用另一个语句(这次是查询)来确保您在该表中确实有一个自动增量主键列。
If you can't use
RETURN_GENERATED_KEYS
, use another statement (a query this time) to doMake sure that you definitely have an auto-increment primary key column in that table.