[英]Why is this query not returning any results?
我正在學校里學習Java,由於某種原因,下面的代碼未返回任何結果? 這段代碼有問題嗎? mysql數據庫中只有一條記錄, studentID
為12 int(10)
)。
public static ResultSet GetByID(int studentID) {
// This method loads the mysql driver and establishes the database connection
Connect();
ResultSet results = null;
try {
String query = "SELECT * FROM student where studentID = ?";
PreparedStatement statement = Connection.prepareStatement(query);
statement.setInt(1, studentID);
results = statement.executeQuery();
} catch (SQLException ex) {
LogException(ex);
} catch (Exception ex) {
System.out.println(ex);
}
// This method terminates the mysql connection.
Disconnect();
return results;
}
調用代碼為:
@Override
public ResultSet query() {
return DB.GetByID(getStudentID()); // this is 12
}
這不會返回null,而只是返回一個空結果集。
只能在連接仍處於打開狀態時使用ResultSet
。 在“斷開連接”之前,請先閱讀它。
如果修復該問題不會給您帶來不同的結果,則最可能的原因是查詢與表中的任何行都不匹配。
您應該養成在finally
塊中關閉連接,流等的習慣,以防止資源泄漏。 (您的講師應該對此進行了解釋。請檢查您的筆記/教科書。)
最后,由於您是初學者,因此需要指出的是,對於方法命名,您應始終遵循公認的Java約定。 Java方法名稱應以小寫字母開頭。 GetByID
應該是getByID
, Disconnect
應該disconnect
。
(並且,如果您的講師/導師沒有這樣做,也沒有因此而停業,則應譴責他/她在未來5年內編寫Visual Basic,以打擊軟件工程行業。)
如果要在關閉連接后返回resultSet ,則必須使用CachedRowSet。 正如StephenC所說,關閉連接后,您的ResultSet為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.