从插入语句获取结果集 [英] Getting resultset from insert statement
问题描述
我有以下代码,我将记录插入到表中.当我尝试获取结果集时,它返回 null.如何将最新添加的行放入结果集中?
i have the below code, where I'm inserting records to a table. When I try to get resultset, it returns null. How to get the latest added row into a resultset?
String sql1 = "INSERT INTO [xxxx].[dbo].[xxxxxx](WORKFLOW_SEQ_NBR," +
" WORKFLOW_LOG_TYPE_CODE, WORKFLOW_STATUS_CODE, DISP_CODE, DISP_USER, DISP_COMMENT, DISP_TITLE, DISP_TS)" +
"VALUES(?,?,?,?,?,?,?,?)";
PreparedStatement pst = connect.prepareStatement(sql1);
pst.setString(1, ...);
pst.setString(2, ...);
...
...
...
pst.executeUpdate();
ResultSet rstest = pst.executeQuery();
// ResultSet rstest = pst.getResultSet();
已解决
添加以下方法转到最后添加的行
added following method to go to the last added row
st.execute("Select * from [xxxx].[dbo].[xxxxxxxxx]");
ResultSet rstest = st.getResultSet();
rstest.afterLast();
GETLASTINSERTED:
while(rstest.previous()){
System.out.println(rstest.getObject(1));
break GETLASTINSERTED;//to read only the last row
}
推荐答案
使用 SQL 语句时,例如 INSERT
、UPDATE
或 DELETE
使用 PreparedStatement
,您必须使用 executeUpdate
,它将返回受影响的行数.在这种情况下,sql 操作根本没有产生 ResultSet
,因此调用 executeQuery 将抛出一个 SQLException
.
When using a SQL statement such as INSERT
, UPDATE
or DELETE
with a PreparedStatement
, you must use executeUpdate
, which will return the number of affeted rows. In this case there is simply no ResultSet
produced by the sql operation and thus calling executeQuery will throw a SQLException
.
如果您确实需要一个 ResultSet
,您必须使用 SELECT
SQL 操作创建另一个语句.
If you actually need a ResultSet
you must make another statement with a SELECT
SQL operation.
有关 PreparedStatement#executeQuery<请参阅 javadoc/a> 和 PreparedStatement#executeUpdate
这篇关于从插入语句获取结果集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!