7

我是得到

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; 错误的 SQL 语法 [从临床医生那里选择 cid、临床医生代码、密码、名字、姓氏,其中临床医生代码 =?];嵌套异常是 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:“字段列表”中的未知列“临床医生”

以下代码出错,您还可以在屏幕截图中看到表格,除了 cid 所有其他属性都是 VARCHAR(45)

临床医生表

行映射器类

public class CClinicianRowMapper implements RowMapper {

@Override
public Object mapRow(ResultSet rs, int line) throws SQLException {
    CClinicianResultSetExtractor extractor = new CClinicianResultSetExtractor();
    return extractor.extractData(rs);
}

}

结果提取器类公共类 CClinicianResultSetExtractor 实现 ResultSetExtractor {

  @Override
  public Object extractData(ResultSet rs) throws SQLException {
    CClinician clinician = new CClinician();
    clinician.setCid(rs.getLong("cid"));
    clinician.setClinicianCode(rs.getString("clinician-code"));
    clinician.setPassword(rs.getString("password"));
    clinician.setFirstName(rs.getString("first-name"));
    return clinician;
  }

}

从表中选择数据的类

public List<CClinician> findClinician(CClinician _clinician) {
    // TODO Auto-generated method stub
    JdbcTemplate select = new JdbcTemplate(dataSource);
    try
    {
    return select.query("select cid, clinician-code, password, first-name, last-name from Clinician where clinician-code= ?",
            new Object[] {_clinician.getClinicianCode()}, new CClinicianRowMapper());

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return null;
}
4

3 回答 3

13

我知道这是一个旧线程,但希望任何偶然发现这个问题的人都会发现这个答案很有用。

我在我的春季应用程序中遇到了同样的异常。根据输出,我认为我的查询存在语法问题。事实证明,我的 mapper 方法实际上存在语法错误。我遇到了这个问题,因为我最初使用与列名不同的字段名创建了我的 Product 类。

public class ProductMapper implements RowMapper<Product> {
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
  Product product = new Product();
  product.setProduct_id(rs.getInt("product_id"));  //was id.  was causing BadSqlGrammarException
  product.setProduct_name(rs.getString("product_name")); //was name.  was causing BadSqlGrammarException
  product.setPrice(rs.getDouble("price"));
  product.setQuantity(rs.getInt("quantity"));
  return product;
   }
}

一旦我进行了上述更改(我的字段名为 product_id 和 product_name),我的应用程序就可以正常工作了。请记住,您对列名或 java 字段所做的任何更改不仅应针对您的查询语句,还应针对您的映射器方法。我看到 OP 正确地做到了这一点,但我认为值得重申。我希望有人觉得这很有帮助。

于 2016-03-23T13:50:24.207 回答
8

为了在列名中使用破折号,您需要使用反引号对它们进行转义。

"SELECT cid, `clinician-code`, password, `first-name`, `last-name` 
     FROM Clinician 
     WHERE `clinician-code` = ?"
于 2012-09-04T20:46:40.990 回答
0

正确检查您的查询语法是否丢失;或额外的逗号 (,) 。“Bad SQL Grammar Exception”仅与 Sql 查询中的语法错误有关。
在使用 Spring JDBC 时,我在以下代码中遇到了同样的错误:

String query= "update student set name=?, city=?, where id=?"; // due to extra comma after city=?,

将代码更改为

String query= "update student set name=? city=?, where id=?"; 

错误已解决。

于 2021-12-09T18:09:07.447 回答