java - How do Prepared Statements prevent SQL injection better than Statements? -
background: have started project using jdbc , mysql simulate bookstore, local. connect database, started out using statement began read when using query multiple times changes parameters, can more efficient use preparedstatement queries. however, thing advantage read how preparedstatements prevent sql injection better.
sources: answers on thread here
google
professors
my question: how preparedstatements prevent sql injection better, or different matter, statements when dealing parametrized queries? confused because, if understand correctly, values still passed sql statement gets executed, it's the programmer sanitize inputs.
you're right could sanitation yourself, , safe injection. more error-prone, , less safe. in other words, doing introduces more chances bugs lead injection vulnerabilities.
one problem escaping rules vary db db. instance, standard sql allows string literals in single quotes ('foo'), sanitation might escape those; mysql allows string literals in double quotes ("foo"), , if don't sanitize well, you'll have injection attack if use mysql.
if use preparedstatement, implementation interface provided appropriate jdbc driver, , that implementation responsible escaping input. means sanitization code written people wrote jdbc driver whole, , people presumably know ins , outs of db's specific escaping rules. they've tested escaping rules more thoroughly you'd test hand-rolled escaping function.
so, if write preparedstatement.setstring(1, name), implementation method (again, written jdbc driver folks db you're using) like:
public void setstring(int idx, string value) { string sanitized = ourprivatesanitizemethod(value); internalsetstring(idx, value); } (keep in mind above code extremely rough sketch; lot of jdbc drivers handle quite differently, principle same.)
another problem non-obvious whether myuserinputvar has been sanitized or not. take following snippet:
private void updateuser(int name, string id) throws sqlexception { mystat.executeupdate("update user set name=" + name + " id=" + id); } is safe? don't know, because there's nothing in code indicate whether name sanitized or not. , can't re-sanitize "to on safe side", because change input (e.g., hello ' world become hello '' world). on other hand, prepared statement of update user set name=? id=? safe, because preparedstatement's implementation escapes inputs before plugs values ?.
Comments
Post a Comment