java.sq.SQLException:未找到列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19062453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:47:49  来源:igfitidea点击:

java.sq.SQLException: Column not found

javasqlspringjdbc

提问by Matthew Moisen

I am receiving the following error:

我收到以下错误:

HTTP Status 500 - Request processing failed; nested exception is
org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar 
[SELECT id, name FROM track WHERE category_id = 1 ORDER BY name]; nested exception is
java.sql.SQLException: Column 'category_id' not found.

But when I copy and paste the very select statement listed in the error into a mysql shell, I get the result, which is expected as the table trackhas the column category_id.

但是,当我将错误中列出的 select 语句复制并粘贴到 mysql shell 中时,我得到了结果,这是预期的,因为该表track具有category_id.

What could be a reason for this error?

此错误的原因可能是什么?

Here is the table create statement for track:

这是表的创建语句track

CREATE TABLE track (
 id SERIAL
,name VARCHAR(50)
,category_id BIGINT UNSIGNED -- This references a serial (bigint unsigned)
,CONSTRAINT track_id_pk PRIMARY KEY (id)
,CONSTRAINT track_category_id_fk FOREIGN KEY
  (category_id) REFERENCES category (id)
);

Here are some lines from my dao class regarding the tracktable:

以下是我的 dao 类中关于track表的一些行:

private static final class TrackMapper implements RowMapper<Track> {
    @Override
    public Track mapRow(ResultSet resultSet, int rowNum) throws SQLException {
        Track track = new Track();
        track.setId(resultSet.getInt("id"));
        track.setName(resultSet.getString("name"));
        track.setCategoryId(resultSet.getInt("category_id"));
        return track;
    }
}
public List<Track> getTracks(int categoryId) {
    String sql = "SELECT id, name FROM track WHERE category_id = " + categoryId + " ORDER BY name";
    return jdbcTemplate.query(sql, new TrackMapper());
}

采纳答案by kevinpeterson

Check your SQL statement -- you need to include the category_idin the column list:

检查您的 SQL 语句——您需要将 包含category_id在列列表中:

String sql = "SELECT id, name, category_id FROM track WHERE category_id = " + categoryId + " ORDER BY name";

String sql = "SELECT id, name, category_id FROM track WHERE category_id = " + categoryId + " ORDER BY name";

It is failing because you're trying to extract category_idfrom the ResultSetand it isn't there.

这是失败的,因为你想提取category_idResultSet与它不存在。