當我嘗試從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);
}
}
}
您關閉while循環之前,甚至得到é機會得到rs.next() – Diversity
看來你在同一個ResultSet對象上運行的executeQuery而rs.next內while循環。是否有一個原因?也許如果你使用了不同的ResultSet對象,它會解決這個問題? –