com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException | JAVA

时间:2014-04-06 11:05:50

标签: java mysql sql jdbc

我想在My java Project中获取表中的条目数。

这是我的代码:

int count = 0;
Statement st = Mysql.con.createStatement();
ResultSet rs= st.executeQuery("select count(*) from keys where spieler =" +p.getName());
while (rs.next()){
    count = rs.getInt(1);
}

我正在关注SQLEXCEPTION

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server version for the 
right syntax to use near 'keys where spieler =Pit910' at line 1

什么是狼?

谢谢!

2 个答案:

答案 0 :(得分:2)

keysreserved MySQL keyword,需要对其进行转义(或者对表格进行转义,或者为其提供不同的名称)。试试这个

PreparedStatement preparedStatement = 
    con.prepareStatement("select count(*) from `keys` where spieler = ?");
preparedStatement.setString(1, p.getName());
ResultSet rs= preparedStatement.executeQuery();
...

答案 1 :(得分:1)

在文本字段值周围使用引号, 您可以选择在字段名称周围使用反引号或使用table_name.field_name

ResultSet rs= st.executeQuery("select count(*) from 
              `keys` where spieler = '" + p.getName() + "' ");