I'm trying to learn how to use MySQL with Java and as the title says, I'm having problems with prepared statements.
I have a MySQL table named temp which contains the values (output directly from MySQL console):
mysql> select * from temp;
+------+-----------------------------------------------+
| id | value |
+------+-----------------------------------------------+
| 1 | this is a first item |
| 2 | this is the second item |
| 3 | This is the third item and slightly redundant |
+------+-----------------------------------------------+
3 rows in set (0.00 sec)
In Java I'm accessing the DB like this:
stmt = conn.prepareStatment("select * from ?");
stmt.setString(1,"temp");
ResultSet rs = stmt.executeQuery(); //This method call throws the exception
stmt.toString
reveals: select * from 'temp'
and the exception message is: 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 ''temp'' at line 1
When I type select * from 'temp'
(The output of stmt.toString()
) directly into the MySQL console I get the exact same message.
As you may have imagined, I'm planning on applying this concept to a JSP webpage, where the table name will be a HTTP GET parameter. So my question is: How do I bind the table name to the prepared statement and if it's not possible (which is the vibe I'm getting from similar questions for PHP), how would I sanitize input for the table name?