为什么我在这个令牌上遇到语法错误?

时间:2013-05-12 03:10:16

标签: sql jdbc

使用JDBC并且我不断收到hoursWorkedToday令牌的语法标记错误,即使它是合法变量,hoursWorked是列名。类型也匹配。

projectUpdate.executeUpdate("INSERT INTO projectLog (hoursWorked, weyerhaeuserWork, sudokuWork,websiteWork, scriptWork," +
                    "tropeWork) VALUES ("hoursWorkedToday +",'"+internWork+"','"+sudokuWork+"', '"+websiteWork+"' ,'"+scriptWork+"' ,'"+tropeWork+"')");

再次在hoursWorkedToday上获取错误,不知道为什么......语法与我运行的其他查询匹配,例如......

workoutUpdate.executeUpdate("INSERT INTO workoutLog (workedOut, milesRan, comments) VALUES (1,"+miles+" ,"+
                    workoutComments+"')");

3 个答案:

答案 0 :(得分:2)

VALUES ("hoursWorkedToday在语法上不正确。您错过了+符号。

我强烈建议您使用PreparedStatement而不是自己组装SQL字符串。 PreparedStatements更快(数据库驱动程序将编译并重用它们),更易于使用,并保护您免受SQL注入。

您可以使用PreparedStatement替换您的查询,如下所示:

PreparedStatement p = connection.prepareStatement("INSERT INTO projectLog(hoursWorked, weyerhaeuserWork, sudokuWork,websiteWork, scriptWork, tropeWork) VALUES (?, ?, ?, ?, ?, ?)");
p.setInt(1, hoursWorkedToday);
...
p.execute();

答案 1 :(得分:0)

  

projectUpdate.executeUpdate(" INSERT INTO projectLog(hoursWorked,   weyerhaeuserWork,sudokuWork,websiteWork,scriptWork," +" tropeWork)   价值观('" + hoursWorkedToday +"''" + internWork +"''" + sudokuWork +"','" + websiteWork +"','" + scriptWork +"&#39 ;,'" + tropeWork +"')");

不确定但有效,但您可以试试。你没有添加''到hoursWorkedToday +

答案 2 :(得分:0)

您错过了结束报价和hoursWorkedToday之间的加号:

projectUpdate.executeUpdate("INSERT INTO projectLog (hoursWorked, weyerhaeuserWork, sudokuWork,websiteWork, scriptWork," +
"tropeWork) VALUES (" + hoursWorkedToday +",'"+internWork+"','"+sudokuWork+"', '"+websiteWork+"' ,'"+scriptWork+"' ,'"+tropeWork+"')");
--                    ^ here