首页 > 解决方案 > 使用 DB2 Select from Table 获取异常

问题描述

我不断收到“java.sql.SQLException:找不到列'id'。” 在 Netbeans 上尝试使用 DB2 从表中选择时。这是我的表创建代码:

string="CREATE TABLE PlayerCollection "
                + "(id integer not null GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),"
                + "name varchar(20),"
                + "height varchar(20),"
                + "weight varchar(20),"
                + "position varchar(20),"
                + "team varchar(20),"
                + "PRIMARY KEY (id))";

这是我从表中选择的代码:

String sql = "select name, height, weight, position, team from PlayerCollection "
                        + "where id=" + strIndex;

为什么即使“id”明确存在于我的表中,我也会收到此异常,我该如何解决?
实际上,我的错误似乎在这一行:

int ind = rs.getInt("id");

"rs"是一个结果集。

标签: javajdbcnetbeansdb2sqlexception

解决方案


结果集仅包含您选择的列,因此您必须id在选择列表中包含该列:

String sql = "select id, name, height, weight, position, team from PlayerCollection "
           + "where id=" + strIndex;

或者因为您在子句中使用id的变量中有 ' 值,所以只需删除以下行:strIndexWHERE

int ind = rs.getInt("id");

从您的代码中,或将其更改为:

int ind = Integer.parseInt(strIndex);

推荐阅读