Search code examples
androidsqlcode-injectionprepare

sql prepared statement not working


I am struggling with this problem and I for some reason I can't solve it.

Connection conn = null;

PreparedStatement ps = null;                                        
String query = "INSERT INTO " + "tags" + "(Name, Income, Expense) VALUES(?,?,?)";
ps = conn.prepareStatement(query);
ps.setString(1, tag);
ps.setString(2, amount_);
ps.setString(3, "0");
ps.executeQuery();

Tag is string from user input, and user still can send SQL injection! WHY?? Also I'm getting this Eclipse error: Null pointer access: The variable conn can only be null at this location.


Solution

  • Your database connection hasn't been initialized. You need to you DriverManager class to obtain a database connection before creating the prepared statement.

    If "tags" is provided by the user your SQL is still potentially vulnerable to an injection attack because the user can specify additional SQL operations instead of a table name. For example, if the user input:

    "users (Name, Income, Expense) VALUES('','',''); drop table accounts; INSERT INTO users ;"
    

    as the value of "tags" the user could insert an extra row into the users table and drop the accounts table. You need to make "tags" part of the prepared statement, replace "tags" with "?" and use setString to assign the value.