从插入语句获取结果集 [英] Getting resultset from insert statement

查看:52
本文介绍了从插入语句获取结果集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,我将记录插入到表中.当我尝试获取结果集时,它返回 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 语句时,例如 INSERTUPDATEDELETE使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆