0

I just learned about prepared statements and now I'm trying to include them to my java program. However I get an exception when I try to add to values to the statement( table and name). When I prepare with only one variable it works fine. What am I doing wrong?

[SQLITE_ERROR] SQL error or missing database (near "?": syntax error)

String sql="SELECT * FROM ? WHERE name = ?";
    try {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, table);
        preparedStatement.setString(2, name);
        ResultSet checkTable = preparedStatement.executeQuery();
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Lau
  • 3,260
  • 5
  • 16
  • 25

3 Answers3

3

That's not how prepared statements work. Oddly enough, you can't use placeholders for table names. The solution being to use something like:

String sql = String.format("SELECT * FROM %s WHERE name = ?", table);

... and proceed with the rest of your code.

Community
  • 1
  • 1
hd1
  • 33,938
  • 5
  • 80
  • 91
0

Prepared statement are for values, a table name is not considered as being a value. So what you try to achieve is not possible.

That would work, though :

String sql="SELECT * FROM any_table_name WHERE name = ?";
try {
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    preparedStatement.setString(1, name);
    ResultSet checkTable = preparedStatement.executeQuery();
} catch (Exception e) {}
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
0

Prepared statements are for column values not table names. You should do it as follows.

String sql = "SELECT * FROM `" + table + "` WHERE name = ?";
Aditya
  • 913
  • 2
  • 7
  • 18