Java SQLite ResultSet不返回任何内容

时间:2018-11-13 01:22:15

标签: java sqlite

我试图从数据库中获取数据,但是当我插入某些东西时它什么也没返回。我不知道我在做什么错。我已经看了很多教程,但是什么都没找到。

    sql = "INSERT INTO optionsetvalue (optionsetid, value, text) VALUES ("+id+", 10000, 'Monday')";
    executeInsert(sql);

    sql = "SELECT * FROM optionsetvalue";
    ResultSet rs = execute(sql, true);
    try {
        while(rs.next())
        {
            System.out.println(rs.getInt("value"));
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

我有这个方法

protected ResultSet execute(String sql, boolean returnResults)
{
    ResultSet results = null;
    if(databaseExists)
    {
        try (Connection conn = DriverManager.getConnection(url);
                Statement stmt = conn.createStatement()) {

            if(returnResults) results = stmt.executeQuery(sql);
            else stmt.execute(sql);

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
    return results;
}

我犯的错误是什么?当我逐步执行代码时,它一定会进入stmt.executeQuery方法。当我运行rs.Next()时,它返回false,因此永远不会进入System.out.println。

protected long executeInsert(String sql)
{
    try(
        Connection conn = DriverManager.getConnection(url);
        PreparedStatement statement = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    ) {

        int affectedRows = statement.executeUpdate();

        if (affectedRows == 0) {
            throw new SQLException("Creating user failed, no rows affected.");
        }

        try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
            if (generatedKeys.next()) {
                return generatedKeys.getLong(1);
            }
            else {
                throw new SQLException("Creating user failed, no ID obtained.");
            }
        }
    } catch(SQLException e)
    {
        System.out.println(e.getMessage());
    }
    return -1;
}

1 个答案:

答案 0 :(得分:0)

您在execute方法中使用try-with-resource,这意味着当您退出try {}时,连接和结果集已关闭,您需要直接从结果集中提取数据并从方法作为自定义类或某些集合类。

一个非常简单的例子

if(returnResults) {
    results = stmt.executeQuery(sql);
    if (results.next()) {
        value = results.getInt(“value”);
        System.out.println(value);
    }
}