简体   繁体   中英

String format ( or similar function ) or PreparedStatement

有什么区别,可以使用什么更好的做法: String.format()并手动插入值或PreparedStatement并将值解析为占位符(更大的代码大小)?

As a general rule, never ever use plain string formatting where PreparedStatement could be used. That latter has knowledge of your database SQL syntax. And will takes care of "shielding" every special characters much better than you.

Failure to follow that rule will result in high risks of SQL Injection in your code.

See Does the preparedStatement avoid SQL injection?

There is a fundamental difference: a PreparedStatement will make whatever it takes so that the values you feed to it (via the .set*() methods) come as "neutral" to the database (or, rather, the "JDBC engine").

Note that PreparedStatement is an interface . As such, when using a JDBC driver for this or that database engine, it will be able to act differently depending upon said engine.

Do not use String.format() for that. Its role is quite different! String.format() cannot prevent SQL injection attacks; PreparedStatement can, unless its implementor did a really, really bad job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM