在我以前的一个问题之一与方法设计我是建议将我的SQL查询实施为参数化查询,而不是一个简单的字符串。

我从未使用参数化查询以前,所以我决定从一个简单的东西开始,采取以下 select 语句:

String select = "SELECT * FROM ? ";

PreparedStatement ps = connection.prepareStatement(select);
ps.setString(1, "person");
.

这给了我以下错误:“[sqlite_error] sql错误或缺少数据库(近”?“:语法错误)”

然后我尝试了一个修改的版本,具有额外的标准;

String select = "SELECT id FROM person WHERE name = ? ";

PreparedStatement ps = connection.prepareStatement(select);
ps.setString(1, "Yui");
.

此版本工作正常,在我的第一个示例中,我错过了参数化查询的点,或者我是错误地构建它们?

谢谢!

有帮助吗?

解决方案

Simply put, SQL binds can't bind tables, only where clause values. There are some under-the-hood technical reasons for this related to "compiling" prepared SQL statements. In general, parameterized queries was designed to make SQL more secure by preventing SQL injection and it had a side benefit of making queries more "modular" as well but not to the extent of being able to dynamically set a table name (since it's assumed you already know what the table is going to be).

其他提示

If you want all rows from PERSON table, here is what you should do:

String select = "SELECT * FROM person";

PreparedStatement ps = connection.prepareStatement(select);

Variable binding does not dynamically bind table names as others mentioned above. If you have the table name coming in to your method as a variable, you may construct the whole query as below:

String select = "SELECT * FROM " + varTableName;
PreparedStatement ps = connection.prepareStatement(select);

Parameterized queries are for querying field names - not the table name!

Prepared statements are still SQL and need to be constructed with the appropriate where clause; i.e. where x = y. One of their advantages is they are parsed by the RDMS when first seen, rather than every time they are sent, which speeds up subsequent executions of the same query with different bind values.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top