【发布时间】:2015-07-31 22:14:50
【问题描述】:
为什么如果我使用 queryFromDb() 从 db 类查询数据库,当它第二次尝试执行 rs.next() 时会得到“ResultSet not open”,而如果我尝试使用 queryFromMain 一切正常?
public class Db {
private String protocol = "jdbc:derby:";
private ResultSet resultSet = null;
private Connection connection = null;
private Statement statement;
public Db(){
try{
Properties props = new Properties();
props.put("user", "user");
props.put("password", "password");
String dbName = "database";
connection = DriverManager.getConnection(protocol + dbName , props);
}
catch(SQLException sqle){
printSQLException(sqle);
}
}
public ResultSet returnValue(String query){
try{
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
}
catch(SQLException sqle){
printSQLException(sqle);
}
return resultSet;
}
public void queryFromDb(){
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM clsbck ORDER BY id");
while(rs.next()){
System.out.println(rs.getString(2));
String str = "INSERT INTO cls rck VALUES 2";
[...]
statement.execute(str);
}
} catch (SQLException e) {
printSQLException(e);
}
}
}
}
public class Main {
private static Db db;
public static void main(String[] args){
db = new Db();
}
public static void queryFromMain(){
ResultSet rs = db.returnValue("SELECT * FROM clsbck ORDER BY id");
try {
while(rs.next()){
String str = "INSERT INTO cls rck VALUES 2";
[...]
db.addValue(str);
}
} catch (SQLException e) {
printSQLException(e);
}
}
}
【问题讨论】:
标签: java sql jdbc derby resultset