Should I be using PreparedStatements for all my database inserts in Java?(我是否应该为我在 Java 中的所有数据库插入使用 PreparedStatements?)
问题描述
在Java中将变量插入数据库之前转义变量的推荐方法是什么?
What is the recommended method for escaping variables before inserting them into the database in Java?
据我了解,我可以使用 PreparedStatement.setString() 来转义数据,但如果我不打算再次运行相同的查询,PreparedStatement 似乎有些不切实际.. 有没有更好的方法来做到这一点而无需准备每个查询?
As I understand, I can use PreparedStatement.setString() to escape the data, but PreparedStatement seems somewhat impractical if I don't plan to run the same query ever again.. Is there a better way to do it without preparing every query?
推荐答案
是的,对所有事情都使用准备好的语句.
Yes, use prepared statements for everything.
它们被解析一次.
They're parsed once.
它们不受 SQL 注入攻击.
They're immune from SQL injection attacks.
它们是更好的设计,因为您必须考虑您的 SQL 及其使用方式.
They're a better design because you have to think about your SQL and how it's used.
如果您认为它们只使用一次,那么您就没有看到全局.总有一天,您的数据或应用程序会发生变化.
If you think they're only used once, you aren't looking at the big picture. Some day, your data or your application will change.
编辑.
为什么准备好的语句会让你思考你的 SQL?
Why do prepared statements make you think about your SQL?
当你组装一个字符串(或简单地执行一个文本块)时,你并没有创建一个新的
PreparedStatement
对象.你只是在执行 SQL——它可以很随意地完成.
When you assemble a string (or simply execute a literal block of text) you aren't creating a new
PreparedStatement
object. You're just executing SQL -- it can be done very casually.
当您必须创建(并保存)PreparedStatement
时,您必须稍微考虑一下封装和责任分配.语句的准备是执行任何 SQL 处理之前的有状态事件.
When you have to create (and save) a PreparedStatement
, you have to think just a tiny bit more about encapsulation, allocation of responsibility. The preparation of a statement is a stateful event prior to doing any SQL processing.
额外的工作量很小,但并非微不足道.这就是人们开始考虑 ORM 和数据缓存层以及优化数据库访问的原因.
The extra work is small, but not insignificant. It's what causes people to start thinking about ORM and a data caching layer, and things like that to optimize their database access.
使用 Prepared 语句,数据库访问不那么随意,更有意.
With Prepared statements, database access is less casual, more intentional.
这篇关于我是否应该为我在 Java 中的所有数据库插入使用 PreparedStatements?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我是否应该为我在 Java 中的所有数据库插入使用 PreparedStatements?


- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01