我想只寫1個execute方法,並在需要時重新使用它,而不用重寫整個事物。以下是我返回ResultSet的方法。如何在關閉Java中的連接之前返回ResultSet
public ResultSet executeSelect() {
Connection con = null;
PreparedStatement prepared = null;
ResultSet rs = null;
try {
con = C_DB.getConnection();
prepared = con.prepareStatement(this.getQuery());
if(!this.midQuery.equals("")) {
int i = 1;
for (String val: this.values) {
prepared.setString(i, val);
i++;
}
}
rs = prepared.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (prepared != null) {
prepared.close();
}
if (con != null) {
con.close();
}
} catch(SQLException e) {
e.printStackTrace();
}
}
return rs;
}
問題是的ExecuteSelect()執行,連接,PreparedStatement和ResultSet中的數據返回前關閉之後,所以我得到這個錯誤java.sql.SQLException: Operation not allowed after ResultSet closed
我希望返回的ResultSet是我的原因,再利用任何對象數據的executeData方法。例如:
C_Query q = new C_Query(dataSearch,"SELECT * FROM people ", " ORDER BY id DESC");
ResultSet rs = q.executeSelect()
ObservableList<C_Person> peopleData = FXCollections.observableArrayList();
while(rs.next()){
C_Person person = new C_Person();
person.setFirstName(rs.getString("firstName"));
person.setLastName(rs.getString("lastName"));
peopleData.add(person);
}
和
C_Query q = new C_Query(dataSearch,"SELECT * FROM cars", " ORDER BY id DESC");
ResultSet rs = q.executeSelect()
ObservableList<C_Car> CarData = FXCollections.observableArrayList();
while(rs.next()){
C_Car car = new C_Car();
car.type(rs.getString("type"));
car.brand(rs.getString("brand"));
CarData.add(car);
}
我該如何解決這個問題?
看看彈簧JDBC來的一個很好的方式,使周圍的JDBC瘦包裝的例子。它使用回調來填充Resultset中的對象。像休眠這樣的ORM功能強大,但學習曲線陡峭。 –