Home » Android » Android SQLite – named parameters

Android SQLite – named parameters

Posted by: admin June 16, 2020 Leave a comment

Questions:

I’m working on Android application that uses SQLite as a local storage. I need to use parameters in sql query but all examples I have found contain unamed parameters, like so:

INSERT INTO SomeTable(ColA, ColB, ColC) VALUES (?,?,?);

I’m wondering – does SQLite on Android supports named parameters? Something like this instead of question marks..

INSERT INTO SomeTable(ColA, ColB, ColC) VALUES (@paramA, @paramB, @paramC);

SQLite itself supports this (according to the documentation https://www.sqlite.org/lang_expr.html).

Thanks in advance

How to&Answers:

The Android database API allows parameter binding only by index.

This does not prevent you from using named parameters in SQL, but you still have to use the correct index to bind them.
This is pretty much useless, except for documentation, or for reusing a parameter:

db.rawQuery("SELECT * FROM Tab WHERE A = @search OR B = @search",
            new String[]{ search });

Answer:

A more android SQLite specific way is to use a ContentValues for sql insert. In the example below. values is a ContentValues and it contains the column name and the value for the column. Columns not in the ContentValues are set to their default value on the insert.

            id = sqlDB.insertOrThrow(RidesDatabaseHandler.TABLE_RIDES,
                    null, values);