Java PreparedStatement检索最后插入的ID

编程入门 行业动态 更新时间:2024-10-27 02:27:41
本文介绍了Java PreparedStatement检索最后插入的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

So how can I escape input and use PreparedStatements in Java?

推荐答案

在 prepareStatement()以及您的查询。然后使用 PreparedStatement 的getGeneratedKeys()来获取包含插入的auto_incremented_id的ResultSet。

pass Statement.RETURN_GENERATED_KEYS in prepareStatement() along with your query. And then use getGeneratedKeys() of PreparedStatement to get the ResultSet containing your inserted auto_incremented_id.

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

更多推荐

Java PreparedStatement检索最后插入的ID

本文发布于:2023-10-13 20:46:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1489030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java   PreparedStatement   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!