简单参数化查询时出错-Java/SQL [英] Error with simple Parameterized Query - Java/ SQL

查看:184
本文介绍了简单参数化查询时出错-Java/SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继上一个问题之后,我与方法设计有关建议将我的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.

我之前从未使用过参数化查询,因此我决定从简单的内容入手,采用以下 Select 语句:

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");

这给了我以下错误:"[SQLITE_ERROR] SQL错误或缺少数据库(在?"附近:语法错误)"

然后我尝试了具有附加条件的修改版本;

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?

谢谢!

推荐答案

简单地说,SQL绑定不能绑定表,只能绑定where子句值.这样做有一些幕后的技术原因,与编译"准备好的SQL语句有关.通常,参数化查询旨在通过防止SQL注入来使SQL更加安全,它还有使查询更加模块化"的副作用,但不能达到动态设置表名的程度(因为假定您已经知道表将是什么.

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

这篇关于简单参数化查询时出错-Java/SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆