NGix
NGix

Reputation: 2662

String format ( or similar function ) or PreparedStatement

Is there a difference and what is better practice to use: String.format() and manually insert values or PreparedStatement and parse values to placeholders (what is more size of code)?

Upvotes: 1

Views: 2611

Answers (2)

fge
fge

Reputation: 121790

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.

Upvotes: 3

Sylvain Leroux
Sylvain Leroux

Reputation: 52040

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?

Upvotes: 4

Related Questions