使用方法next()时关闭异常ResultSet

时间:2013-12-19 00:56:57

标签: java sql jdbc

当我尝试从while(sr.next())向表中插入一个值时,我遇到了next()方法的问题,它抛出了ResultSet Exception但是当我从中删除插入查询时虽然它工作的主体,所以当我正在训练在while体中插入值时,为什么关闭ResultSet是代码

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class SqlServerJDBC {


    public static void main(String[] args) throws IOException {
        String line, dis;
        float totalPrice = 0;
        Scanner scan= new Scanner(System.in);

        try {
                    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                    System.out.println("# - Driver Loaded");

                    Connection con =               DriverManager.getConnection("jdbc:odbc:books_DSN");
                    System.out.println("# - Connection Obtained");

                    Statement stmt = con.createStatement();
                    System.out.println("# - Statement Created");

                    String createTableOrder =  "create table viewOrder"
                                            + "(title_name VARCHAR(40),"
                                            + "price DECIMAL(5,2),"
                                            + "pages INT,"
                                            + "au_fname VARCHAR(15),"
                                            + "au_lname VARCHAR(15),"
                                            + "pub_name VARCHAR(20),"
                                            + "city VARCHAR(15),"
                                            + "country VARCHAR(15))";



                    stmt.executeUpdate(createTableOrder);
                    System.out.println("Created table in given database...");

                    ResultSet rs = stmt.executeQuery("SELECT title_name,price FROM titless");
                    System.out.println("# - Query Executed\n");

                    while(rs.next()){
                        System.out.println("title: " +rs.getString("title_name") + "\tprice: " + rs.getFloat("price"));             
                    }   

                        do {
                            System.out.println("\nEnter the name of the book...");
                            line = scan.nextLine();
                            rs = stmt.executeQuery("select title_name,price,pages,au_fname"
                                    + ",au_lname,pub_name,authorss.city,country "
                                    + " from titless inner join title_authorss on titless.title_id = title_authorss.title_id "
                                    + " inner join authorss on title_authorss.au_id = authorss.au_id"
                                    + " inner join publisherss on publisherss.pub_id = titless.pub_id"
                                    + " where titless.title_name like "+"'"+line+"'");


                            /*here is the problem */
                                while(rs.next()){

                                String insertIntoTableOrder =("INSERT INTO viewOrder "
                                        + " VALUES ('"+rs.getString("title_name")+"',"+rs.getFloat("price")+","+rs.getInt("pages")+""
                                        + ",'"+rs.getString("au_fname")+"','"+rs.getString("au_lname")+"',"
                                        + "'"+rs.getString("pub_name")+"','"+rs.getString("city")+"','"+rs.getString("country")+"')");
                                stmt.executeUpdate(insertIntoTableOrder);

                                totalPrice = totalPrice + rs.getFloat("price"); 


                            }


                            System.out.println("Total Price = " + totalPrice);
                            System.out.println("Do you want add more books ??");
                            System.out.println("Y/N...");
                            dis = scan.nextLine();


                        } while (dis.equalsIgnoreCase("y")); 



                         con.close();
                         stmt.close();   
                         rs.close();

                    System.out.println("# - Resources released");

                } catch (SQLException | ClassNotFoundException ex) {
                            System.out.println("Error : "+ex);
           }

    }   

  }

here is the output

2 个答案:

答案 0 :(得分:2)

根据文档:

  

默认情况下,每个Statement对象只能同时打开一个ResultSet对象。因此,如果读取一个ResultSet对象与另一个ResultSet对象的读取交错,则每个ResultSet对象必须由不同的Statement对象生成。如果存在一个开放的对象,则Statement接口中的所有执行方法都会隐式关闭该语句的当前ResultSet对象。

http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html

您正在遍历ResultSet并重复使用相同的Statement来执行INSERT。执行插入后,您正在迭代的ResultSet关闭,下一次调用rs.next()会抛出该异常。您需要使用新的Statement在循环内执行插入查询。

那就是说,你真的应该为你的SQL使用预准备语句。它在阅读代码方面更加清晰,而且在为您处理任何必要的引用时更不容易出错。

String statementString = "INSERT INTO viewOrder VALUES (?,?,?,?,?,?,?,?)";
PreparedStatement pStmt= con.prepareStatement(statementString);
while(rs.next())
{
    pStmt.setString(1, rs.getString("title_name"));
    pStmt.setFloat(2, rs.getFloat("price"));
    pStmt.setInt(3, rs.getInt("pages"));
    pStmt.setString(4, rs.getString("au_fname"));
    pStmt.setString(5, rs.getString("au_lname"));
    pStmt.setString(6, rs.getString("pub_name"));
    pStmt.setString(7, rs.getString("city"));
    pStmt.setString(8, rs.getString("country"));
    pStmt.execute();

    totalPrice = totalPrice + rs.getFloat("price"); 
}

答案 1 :(得分:0)

您需要另一个Statement对象。在单个Statement上调用第二个查询,同时迭代ResultSet(与相同的语句上的游标相关联)是一个坏主意。