The reason you bind your values ββto the query is to prevent SQL injection attacks .
Essentially, you submit your request (including placeholders) to your database and say: "My next request will be this form and no one else!". When an attacker enters another query line (for example, through a form field), the database says: "Hey, this is not the request that you said you will send!" and gives you an error.
Since the commands (which can be entered into your actual query, as shown in the related article) are strings, the string-datatype type is more "dangerous". If the user tries to insert some code in your field that should only accept numbers, and you try to bring / analyze the input data to an integer (before placing the value in your query), you will immediately get an exception. There is no such good security with the string. Therefore, they probably need to escape. This may be the reason that all binding values ββare interpreted as strings.
The above is fake ! It doesn't matter if the arguments you bind are strings or integers, all of them are equally dangerous. In addition, pre-checking your values ββin the code leads to a lot of boilerplate code, error prone and inflexible!
To prevent the application from using SQL injection, as well as to speed up several write operations to the database (using the same query with different values), you should use "prepared statements". The correct class for writing to the database in the Android SDK is SQLiteStatement .
To create a prepared statement, you use the compileStatement() -method of your SQLiteDatabase -object and bind the appropriate values ββ(which will be replaced with ? -Marks in your query) using the correct bindXX() -method (which are inherited from SQLiteProgram ):
SQLiteDatabase db = dbHelper.getWritableDatabase(); SQLiteStatement stmt = db.compileStatement("INSERT INTO SomeTable (name, age) values (?,?)"); // Careful! The index begins at 1, not 0 !! stmt.bindString(1, "Jon"); stmt.bindLong(2, 48L); stmt.execute(); // Also important! Clean up after yourself. stmt.close();
An example is taken from this old question: how to use prepared statements in SQlite in Android?
Unfortunately, SQLiteStatement does not have an overload that returns Cursor , so you cannot use it for SELECT -statements. For them you can use rawQuery(String, String[]) -method SQLiteDatabase :
int number = getNumberFromUser(); String[] arguments = new String[]{String.valueOf(number)}; db.rawQuery("SELECT * FROM TABLE_A WHERE IFNULL(COLUMN_A, 0) >= ?", arguments);
Note that rawQuery() -method accepts a String array for argument values. It really doesn't matter, SQLite automatically converts to the correct type. As long as the string representations match what you expect in the SQL query, everything is fine.