문제

이전 질문 중 하나에서 방법 디자인 SQL 쿼리를 간단한 문자열과 반대로 매개 변수화 된 쿼리로 구현하도록 권고합니다.

나는 매개 변수화 된 쿼리를 사용하지 않았기 때문에 단순한 것을 시작하기로 결정하고 다음 select 문을 취하십시오.

String select = "SELECT * FROM ? ";

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

다음 오류가 발생합니다. [sqlite_error] SQL 오류 또는 누락 된 데이터베이스 (근처 ": 구문 오류)"

i 그런 다음 추가 기준이있는 수정 된 버전을 시도했습니다.

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