简体   繁体   English

SQL语句在空表上返回结果集

[英]SQL statement returns a resultset on an empty table

        String sql = "Select MAX(ORDERLINEID) From ORDERLINESTABLE";
        ResultSet rst;
        rst = stmt.executeQuery(sql);

        if(rst.next())
        {
            next = rst.getInt("ORDERLINEID");
            next++;
        }

I have a table called ORDERLINESTABLE in my database which is currently empty. 我的数据库中有一个名为ORDERLINESTABLE的表,该表当前为空。 I have run the above code with the aim is to get the highest integer stored in the ORDERLINEID column allowing me to increment it when adding items to the database. 我运行上面的代码的目的是要获取存储在ORDERLINEID列中的最高整数,允许我在向数据库添加项目时对其进行递增。

I expected this query to return nothing as the table is empty but when debugging I noticed that the search is returning true for the rst.next() method. 我希望此查询什么都不会返回,因为表为空,但是在调试时,我注意到rst.next()方法的搜索返回true。

Does anyone have any idea why this would be? 有谁知道为什么会这样吗? I have looked at the resultset.next() documentation and as far as I can see it should return false. 我查看了resultet.next()文档,据我所知它应该返回false。

When in doubt, look at your data. 如有疑问,请查看您的数据。 Here is a sample query from any db engine. 这是来自任何数据库引擎的示例查询。

select max(field) maxValue
from table
where 1=3

It will yield 它会产生

maxValue
Null

In other words, your query is returning one record with a value of null. 换句话说,您的查询将返回一个值为null的记录。

It is much better to fetch the ORDERLINEID filled in by the database after the INSERT statement. 最好在INSERT语句之后获取数据库填充的ORDERLINEID。 Make the column ORDERLINEID of type INT AUTOINCREMENT. 使列ORDERLINEID的类型为INT AUTOINCREMENT。

String sql = "INSERT INTO ORDERLINESTABLE(xxx, yyy) VALUES (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
    stmt.setString(1, xxx);
    stmt.setInt(2, yyy);
    int updateCount = stmt.executeUpdate(); // 1
    try (ResultSet id = stmt.getGeneratedKeys()) {
        if (id.next()) { // 'if' as just 1 row inserted.
            int orderLineId = id.getInt(1); // 1 key per row.
        }
    }
}

Java has a database independent way to fetch the generated keys of an INSERT. Java具有一种独立于数据库的方式来获取INSERT的生成键。 That is a lot safer than taking the MAX afterwards or before, in a multi-user environment. 这比在多用户环境中事后或事前使用MAX更为安全。

Scenarios for wrong IDs are numerous in a multiuser environment: 在多用户环境中,错误ID的情况很多:

  • first SELECT 首先选择
  • second SELECT 第二个SELECT
  • second increment for new ID 新ID的第二个增量
  • first increment for new ID 新ID的第一个增量
  • first INSERT 第一次插入
  • second INSERT 第二次插入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM