代码之家  ›  专栏  ›  技术社区  ›  sproketboy

SQLServerException:语句在执行SQL时未返回结果集

  •  8
  • sproketboy  · 技术社区  · 15 年前

    我使用的是sqljdbc4.jar(sqljdbc_2.0)版本。

    我正在执行insert+select back以获取如下标识:

    BEGIN 
    INSERT INTO DateRangeOptions (Description,Code) 
    VALUES ('dateRange.quickPick.option.all','ALL');  
    SELECT SCOPE_IDENTITY()  
    END
    

    我得到:

    com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
    

    这条线是:

    st.executeQuery(updateQuery)
    

    有什么想法吗?

    3 回复  |  直到 15 年前
        1
  •  8
  •   Danny G    12 年前

    已从SQL 2000升级到SQL 2005,并切换到Microsoft SQL Server 2005 JDBC驱动程序版本1.2。执行insert后接select scope_identity()时出现错误“语句没有返回结果”。我使用executeUpdate()和getGeneratedKeys而不是executeQuery解决了该问题。这是前后代码。

    注意:本例中使用的连接是java.sql.connection,而不是com.microsoft.sqlserver.jdbc.sqlserver connection。

    SQL 2000代码

    String  dbURL = "jdbc:sqlserver" + "://" + dbServer + ":" +
                     dbServerPort + ";SelectedMethod=cursor;databaseName="
                               + dbName + ";user=xxx;password=xxx";
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    java.sql.Connection connection = DriverManager.getConnection(dbURL);
    sql = "insert into Contact (name) values ('ABC'); SELECT SCOPE_IDENTITY()";
    PreparedStatement ps = connection.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();
    if (rs.next()) {
         long id = rs.getLong(1);
         System.out.println("Id=" + id);
    }
    

    SQL 2005代码

    String  dbURL = "jdbc:sqlserver" + "://" + dbServer + ":" +
                     dbServerPort + ";SelectedMethod=cursor;databaseName="
                               + dbName + ";user=xxx;password=xxx";
    
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    java.sql.Connection connection = DriverManager.getConnection(dbURL);
    sql = "insert into Contact (name) values ('ABC'); SELECT SCOPE_IDENTITY()";
    PreparedStatement ps = connection.prepareStatement(sql);
    ps.executeUpdate();  // do not use execute() here otherwise you may get the error
                         // The statement must be executed before 
                         // any results can be obtained on the next
                         // getGeneratedKeys statement.
    
    ResultSet rs = ps.getGeneratedKeys();
    if (rs.next()) {
         long id = rs.getLong(1);
         System.out.println("Id=" + id);
    }
    
        2
  •  1
  •   Hassan Syed    15 年前

    插入的行失败,因此没有标识?在Java中生成断点查询,复制查询字符串,并在Management Studio中运行它,以查看结果是什么。这可能表明你做错了什么。

        3
  •  1
  •   BalusC    15 年前

    有升级驱动程序的选项吗?那你就可以用 Statement#getGeneratedKeys() . 另请参阅本文: http://msdn.microsoft.com/en-us/library/ms378445%28SQL.90%29.aspx

    如果这不是一个选项,那么您需要启动 INSERT SELECT 在同一连接上彼此分开。