SQL injection can wipe your data or leak entire tables—but
PreparedStatement stops it cold. In this post, I’ll show you the only safe way to embed user input in a SQL query.
Here’s a straightforward example that takes
name and email directly as parameters:public insertUser(String name, String email) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = setupTheDatabaseConnectionSomehow();
stmt = conn.prepareStatement("INSERT INTO person (name, email) values (?, ?)");
stmt.setString(1, name);
stmt.setString(2, email);
stmt.executeUpdate();
}
finally {
try {
if (stmt != null) { stmt.close(); }
}
catch (Exception e) {
// log this error
}
try {
if (conn != null) { conn.close(); }
}
catch (Exception e) {
// log this error
}
}
}
No matter what characters
name and email contain—even a malicious string like '; DROP TABLE person; --—they are treated purely as data. The INSERT statement structure remains intact; the parameters never interfere with the SQL syntax.
Match each column’s data type with the appropriate
set* method. For an INTEGER column, call setInt; for a DATE, use setDate, and so on. The official PreparedStatement documentation lists every getter and setter you’ll need. One thing to keep in mind: modern Java lets you replace the repetitive finally block with a try‑with‑resources statement, which closes connections and statements automatically.
No comments :
Post a Comment
Your Comment and Question will help to make this blog better...