SQL Query works in workbench but gives syntax error in java

余生颓废 提交于 2019-12-25 01:47:00

问题


I ran the query in both sql Workbench and in the executeUpdate() method in java:

in Workbench:

INSERT INTO recentsearches (name) VALUES ("blah");

in java:

statement.executeUpdate("INSERT INTO recentsearches (name) VALUES (\""+name+"\""));

Assuming name = "blah". But I get a syntax error from running the query in java, I've already checked the string value for name. It definitely comes up as "blah", and I didn't forget the speech marks around string values, yet I still get a syntax error.

The error I get in my console is:

check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1


回答1:


Try to use:

"INSERT INTO recentsearches (name) VALUES("+name+")"; 

My advice, use PreparedStatement because it has:

-Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.

-Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the values



来源:https://stackoverflow.com/questions/29348428/sql-query-works-in-workbench-but-gives-syntax-error-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!