Reputation:
In my code I have to insert multiple values with a single insert query. For
example INSERT INTO table_name (column_1, column_2) VALUES (value1, val1),(value2,value)
.
To prevent SQL injection I found the below sample.
SQLiteDatabase db = dbHelper.getWritableDatabase();
SQLiteStatement stmt = db.compileStatement(“SELECT * FROM Country WHERE code = ?”);
stmt.bindString(1, “India”);
stmt.execute();
But how does compileStatement
help in case of my code?
Upvotes: 0
Views: 1331
Reputation: 3076
The danger of an sql-injection is when a string representing data is interpreted as SQL code. If the string is user defined, then the user (or someone else exterior to your program) can alter the database in unpredictable ways.
The method compileStatement
receives a string that should only contain sql code, or at the very least not contain any variable that is changed in runtime.
The real help in preventing the sql-injection is in bindString
, since it expects a user defined string, so it makes sure to escape any special character within it so no part of the string is interpreted as SQL code.
For example, using "Indina\"; DROP TABLE some_important_table"
might drop some_important_table
if the string is used on its own, because the \";
ends the current statement being executed. But when used in bindString
, \"
is taken as literal "
and the statement just looks for a country with the code Indina"; DROP TABLE some_important_table
.
Of course, in your example you are using a constant String so it won't make much of a difference, but it is good practice and will ensure future changes won't introduce the danger of sql-injection when this code is used.
Upvotes: 1