我是否应该为我在 Java 中的所有数据库插入使用 PreparedStatements?

2022-01-24 00:00:00 connection mysql prepared-statement java

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

  1. 它们被解析一次.

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

相关文章