java sql 参数化查询,简单参数化查询时出错-Java / SQL

Following on from one of my previous questions to do with method design I was advised to implemented my SQL queries as a parameterized query as opposed to a simple string.

I've never used parameterized queries before so I decided to start with something simple, take the following Select statement:

String select = "SELECT * FROM ? ";

PreparedStatement ps = connection.prepareStatement(select);

ps.setString(1, "person");

This gives me the following error: "[SQLITE_ERROR] SQL error or missing database (near "?": syntax error)"

I then tried a modified version which has additional criteria;

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

PreparedStatement ps = connection.prepareStatement(select);

ps.setString(1, "Yui");

This version works fine, in the my first example am I missing the point of parameterized queries or am I constructing them incorrectly?

Thanks!

解决方案

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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值