2017-11-18 285 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