2017-11-18 328 views
0

即使查詢正常,我試圖從另一個類中檢索的結果集也會返回null。我試圖根據數據庫中保存的記錄初始化我的對象,這意味着如果最初有一個在sqlite中的記錄,我用最新的日期檢索一個記錄。不過,我嘗試從mysql數據庫中檢索最早的一個。是應該檢索結果從MySQL數據庫設置的代碼是這樣的:其他類的空結果語句

public ResultSet lowestDate() throws SQLException { 
    ResultSet rs1 = null; 
    String resultQuery = "SELECT * FROM alarm ORDER BY `timestamp` ASC LIMIT 1"; 
    rs1 = stmt.executeQuery(resultQuery); 
    return rs1; 
} 

聲明初始化globally.And我把這個在另一類是這樣的:

public void setLastAlarm() throws SQLException, ParseException { 
    String liteQuery = "SELECT * FROM alarm_entries ORDER BY date(`timestamp`) DESC LIMIT 1"; 
    conn.connectLite(); 
    Connection getCon = conn.getLiteConnection(); 
    try { 
     stmt = getCon.createStatement(); 
    } catch (SQLException e) { 
     e.printStackTrace(); 
    } 
    try { 
     rs = stmt.executeQuery(liteQuery); 
     if (rs.next()) { 
      //while (rs.next()) { 
      nuDate = rs.getString("timestamp"); 
      newDate = format.parse(nuDate); 
      lastAlarm.setBacklogId(rs.getBytes("backlog_id")); 
      lastAlarm.setTimestamp(newDate); 
      //} 
     } 
     else{ 
      rsq=mysqlConnection.lowestDate(); 
      lastAlarm.setTimestamp(format.parse(rsq.getString("timestamp"))); 
      lastAlarm.setBacklogId(rsq.getBytes("backlog_id")); 
     } 
    }catch (Exception e){ 
     e.printStackTrace(); 
    } 
} 

public void run() { 
    try { 
     setLastAlarm(); 

回答

0

你永遠不會調用ResultSet#next()上結果集從lowestDate()輔助方法返回。因此,遊標永遠不會前進到結果集中的第一個(也是唯一)記錄。但是我認爲用這種方式來考慮JDBC代碼是一個壞主意。相反,只是內聯的兩個查詢是這樣的:

try { 
    rs = stmt.executeQuery(liteQuery); 
    if (rs.next()) { 
     nuDate = rs.getString("timestamp"); 
     newDate = format.parse(nuDate); 
     lastAlarm.setBacklogId(rs.getBytes("backlog_id")); 
     lastAlarm.setTimestamp(newDate); 
    } 
    else { 
     String resultQuery = "SELECT * FROM alarm ORDER BY timestamp LIMIT 1"; 
     rs = stmt.executeQuery(resultQuery); 
     if (rs.next()) { 
      String ts = rs.getString("timestamp"); 
      lastAlarm.setTimestamp(format.parse(ts)); 
      lastAlarm.setBacklogId(rs.getBytes("backlog_id")); 
     } 
    } 
} catch (Exception e){ 
    e.printStackTrace(); 
} 
+0

它沒有工作,它只是跳過整個事情,爲什麼會這樣。當我查詢相同的查詢返回的數據 – Morbidity

+0

那麼也許你的第一個查詢從不空虛。你檢查過你的表中的實際數據嗎? –

+0

是的我的意思是我檢查了表格中的數據,並且查詢在那裏工作 – Morbidity