I can't find the correct syntax of the following query in java,please help me.
String st = "SELECT COUNT('"+id+"') FROM '"+selected_table+"' ";
String st = "SELECT COUNT('"+id+"') FROM '"+selected_table+"'";
I think that the mistake is how to end the query...
Since I got the error Check the manual that corresponds to your MySQL server version for the right syntax to use near ''Customer'' at line 1
when I choose Customer table
-
6Be careful with forming queries by concatenating strings that originate from the client since that opens up an injection vulnerability.Hyangelo– Hyangelo2012年07月25日 20:55:39 +00:00Commented Jul 25, 2012 at 20:55
-
@Hyangelo, +1 for good point, but you think (given the implications from the quality of the question) that OP would understand the importance of that?mre– mre2012年07月25日 20:57:02 +00:00Commented Jul 25, 2012 at 20:57
-
2@mre good point as well but just felt I had to at least point out the potential danger.Hyangelo– Hyangelo2012年07月25日 20:58:14 +00:00Commented Jul 25, 2012 at 20:58
-
and in case the OP doesn't know what exactly you mean: en.wikipedia.org/wiki/Sql_injectionyshavit– yshavit2012年07月25日 21:00:43 +00:00Commented Jul 25, 2012 at 21:00
-
since I am beginner , can you give some tips ,e.g which is the best way to combine Java code with SQL statementsmichaalis– michaalis2012年07月25日 21:16:55 +00:00Commented Jul 25, 2012 at 21:16
4 Answers 4
You want to use backticks instead of single quotes around your object names.
String st = "SELECT COUNT(`"+id+"`) FROM `"+selected_table+"` ";
Comments
Table names should be surrounded by tick marks (`), not single quotes (')
String st = "SELECT COUNT('"+id+"') FROM `"+selected_table+"`";
^ use tick marks ^
Comments
What are the values of id and selected_table? What is the actual query string that is sent to the database?
Also, it's rarely a good idea to manually build a query like this using string concatenation. This makes it very easy for a bug to result in a gaping security hole, and it's a lot more difficult (and risky) to try to secure this approach than it is to just do it right.
2 Comments
Looks from your query that you are enclosing your id and selected_table in single quotes... For example, SELECT COUNT('ID') FROM 'CUSTOMER' which is wrong. should be in backtics `` or nothing...