Wideem Wideem - 1 year ago 92
SQL Question

Select with prepared statements Java

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

hd1 hd1
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download