Deva
Deva

Reputation: 3949

android SQLiteDatabase.insert vs executeSQL

I am working on an app which has multiple db insert/update queries and throughout the app i have used

SQLiteDatabase.insert(String table, String nullColumnHack, ContentValues values)

method for inserting any data to any table. What i mean by this is i create a ContentValues object and put all my values as key/value pair inside this object and pass it on to this this method.

contentValues.put("col1", valueCol1);
contentValues.put("col2", valueCol2);
contentValues.put("col3", valueCol3);

So just wanted to check if this way of inserting records to a sqlite table is better or is it better to use executeSQL [ From SQLinjection standpoint]. I do understand as per the documentation here

[http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#execSQL(java.lang.String)][1]

that its recommended to use insert over execSQL. But which is more prone to SQLInjections if at all one is. Any inputs/suggestions.

Upvotes: 0

Views: 1580

Answers (1)

GVillani82
GVillani82

Reputation: 17439

As suggested in the page that you linked

"Instead, you're encouraged to use insert(String, String, ContentValues), update(String, ContentValues, String, String[]), et al, when possible."

you should use insert() when it is possible.

To avoid SQL injection requests, you need to clearly delineate between the SQL statement and the data it includes. The ContentProvider’s query(), update(), and delete()methods and Activity’s managedQuery() method all support parameterization. These methods all take the “String[] selectionArgs” parameter, a set of values that get substituted into the query string in place of “?” characters, in the order the question marks appear. This provides clear separation between the content of the SQL statement in the “selection” parameter and the data being included. [Mobile Application Security]

So, insert() method like update() or delete() should be sql-injection free.

You should always use parametrized query methods, supported by Content Provider:

When accessing a content provider, use parameterized query methods such as query(), update(), and delete() to avoid potential SQL injection from untrusted sources. Note that using parameterized methods is not sufficient if the selection argument is built by concatenating user data prior to submitting it to the method.

reference here

Upvotes: 1

Related Questions