0

i want to get the Number of Entries in a table in My java Project.

This is my code:

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

I am getting following 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

What is worng?

Thanks!

3
  • Is the spieler a text field in the DB? Commented Apr 6, 2014 at 11:07
  • 1
    You should never use manually concatenated queries, always go for a PreparedStatement, otherwise you are vulnerable to SQL Injeqtion. see bobby-tables.com Commented Apr 6, 2014 at 11:15
  • @Reimeus Yes it is a text field! Commented Apr 6, 2014 at 11:19

2 Answers 2

2

keys is a reserved MySQL keyword which needs to be escaped (either that or ALTER the table to give it a different name). Try this

PreparedStatement preparedStatement = 
    con.prepareStatement("select count(*) from `keys` where spieler = ?");
preparedStatement.setString(1, p.getName());
ResultSet rs= preparedStatement.executeQuery();
...
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that works for me. I have a Insert Command with the Same error: Mysql.Update("INSERT INTO keys (spieler,key) VALUES ('" + p.getName() + "', '" + key + "')");
same applys there - con.prepareStatement("INSERT INTO ``keys`` (spieler, key) VALUES (?, ?)") - some formatting issues should be single backticks around keys – Reimeus 6 mins ago
1

Use quotes around text field values, You can optionally use backtick around field name or use table_name.field_name

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

1 Comment

Now i get this Error: [13:13:42 INFO]: 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.