Ошибка с простым параметризованным запросом - Java / SQL

StackOverflow https://stackoverflow.com/questions/5491107

Вопрос

Следуя на одном из моих предыдущих вопросов, чтобы сделать с Дизайн метода I былрекомендуется реализовать мои SQL-запросы в качестве параметризованного запроса в отличие от простой строки.

Я никогда не использовал параметризованные запросы раньше, поэтому я решил начать с чего-то простого, возьмите следующую Выбор Заявление:

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