【问题标题】:Null result statement from other class其他类的空结果语句
【发布时间】:2018-05-02 01:29:47
【问题描述】:

我试图从另一个类中检索的结果集返回 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;
}

语句是全局初始化的。我在另一个类中这样调用它:

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();

【问题讨论】:

    标签: java mysql sqlite jdbc resultset


    【解决方案1】:

    您永远不会在从 lowestDate() 辅助方法返回的结果集上调用 ResultSet#next()。因此,游标永远不会前进到结果集中的第一个(也是唯一一个)记录。但我认为以这种方式分解 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();
    }
    

    【讨论】:

    • 它不起作用,它只是跳过整个事情,为什么会发生这种情况?当我查询相同的查询时它返回数据
    • 那么也许您的第一个查询永远不会为空。您检查过表中的实际数据吗?
    • 是的,我的意思是我检查了表中的数据并且查询在那里工作
    • 您将不得不使用调试器单步执行您的代码。我已经指出了几个问题,但在我的回答中我没有看到代码本身有任何问题。
    猜你喜欢
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多