2013-12-19 178 views
-1

當我嘗試從while(sr.next())中插入值到表中時,我遇到了next()方法的問題,但它拋出ResultSet異常但當我從while循環體取出插入查詢這麼努力,爲什麼ResultSet中被關閉,當我訓練的同時,身體在這裏插入值是代碼當使用方法next()時關閉結果集

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

+0

您關閉while循環之前,甚至得到é機會得到rs.next() – Diversity

+0

看來你在同一個ResultSet對象上運行的executeQuery而rs.next內while循環。是否有一個原因?也許如果你使用了不同的ResultSet對象,它會解決這個問題? –

回答

0

你需要另一個Statement對象。在迭代ResultSet(綁定到與相同的語句上的遊標)時,在單數Statement上調用第二個查詢是個壞主意。

2

按照文檔:

默認情況下,只有每一個Statement對象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

似乎也不是問題。因爲在這種情況下,你只是得到某種數據庫資源異常。在它旁邊,我認爲必須有一些合乎邏輯的問題。 – Diversity

+0

呃,不......他正在做我剛剛說的話,並且收到了人們期望的確切例外。沒有「邏輯問題」如果他爲插入使用單獨的語句,它將工作正常。 –

相關問題