Search code examples
javamysqlspringjdbc

Bad Sql Grammar exception in JDBC spring


I am the getting

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select cid, clinician-code, password, first-name, last-name from Clinician where clinician-code= ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'clinician' in 'field list'

error on the following code, You can also see the Table in the screen shot, except for cid all other attributes are VARCHAR(45)

Clinician Table

Row mapper class

public class CClinicianRowMapper implements RowMapper {

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

}

Result Extractor Class public class CClinicianResultSetExtractor implements 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;
  }

}

Class for selecting data from table

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;
}

Solution

  • In order to use a dash in the column names, you need to escape them with back ticks.

    "SELECT cid, `clinician-code`, password, `first-name`, `last-name` 
         FROM Clinician 
         WHERE `clinician-code` = ?"