Nested Queries in SQLite3 Android

2019-09-15 17:59发布

问题:

I want to execute a query something like :

INSERT INTO MyTable VALUES(datetime('now'));

Where MyTable has schema:

CREATE TABLE MyTable(
mydate DATETIME
)

When executed in SQLite Manager query runs perfectly inserting the current datetime value in mydate column of MyTable.

But when executed using

ContentValues cv=new ContentValues();
cv.put(MyTable.mydate,"datetime('now')");
getContentResolver.insert(MyTable.CONTENT_URI,cv);

The value in mydate reads datetime('now') and not the actual current date and time.

I am performing all this from a ContentProvider.

How can I fix this ?

回答1:

You cannot use SQLite functions in calls to query(), whether query() is called on a SQLiteDatabase or on a ContentResolver.

You can embed calls to SQLite functions in a SQL statement executed via rawQuery() on a SQLiteDatabase, but that may not help you much if you wish to wrap your database access in a content provider.

The simplest answer is for you to adjust your schema such that mydate has a default value of datetime('now'), then just ignore that column when you are inserting your data.