传递表名作为预准备语句的参数 [英] Passing table name as parameter of prepared statement
问题描述
我正在尝试学习如何在Java中使用MySQL,正如标题所说,我在准备语句时遇到问题。
I'm trying to learn how to use MySQL with Java and as the title says, I'm having problems with prepared statements.
我有一个名为temp的MySQL表,其中包含值(直接从MySQL控制台输出):
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)
在Java中,我正在访问这样的数据库:
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
揭示:从'temp'
中选择*,并且异常消息为:您的SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在第1行的''temp''附近使用正确的语法
当我输入时选择*从'temp'
( stmt.toString()
的输出)直接进入MySQL控制台我得到了完全相同的消息。
When I type select * from 'temp'
(The output of stmt.toString()
) directly into the MySQL console I get the exact same message.
正如您可能想象的那样,我计划将此概念应用于JSP网页,其中表名称将是HTTP GET参数。所以我的问题是:如何将表名绑定到准备好的语句,如果不可能(这是我从PHP的类似问题得到的氛围),我将如何清理表名的输入?
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?
推荐答案
您不能使用 stmt.setString()
或 setInt()
表名的函数,仅对列值有效。
You can not use stmt.setString()
or setInt()
function for table name, it is valid only for column values.
这篇关于传递表名作为预准备语句的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!