插入所有值为 AutoIncrement 或 Default 的记录

Insert record with all values as AutoIncrement or Default

我有一个包含 2 列的 table。

  1. key - 主键,自增
  2. 时间戳 - 日期时间,默认 -> CURRENT_TIMESTAMP

我试图在 SqliteOpenHelper 对象的帮助下在此 table 中插入一个值。但它抛出一个异常:

public void logTime() {

    SQLiteDatabase db = getWritableDatabase();

    db.insert(TABLE_LOG_TIME, null, new ContentValues());
}

异常:

E/SQLiteLog: (1) near "null": syntax error
E/SQLiteDatabase: Error inserting 
      android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: INSERT INTO log_time(null) VALUES (NULL)
      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
      at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
      at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
      at com.livinglifetechway.mytime.db.DatabaseHelper.logScreenUnlock(DatabaseHelper.java:62)
      at com.livinglifetechway.mytime.ScreenUnlockBroadcastReceiver.onReceive(ScreenUnlockBroadcastReceiver.java:25)
      at android.app.ActivityThread.handleReceiver(ActivityThread.java:2732)
      at android.app.ActivityThread.access00(ActivityThread.java:153)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1428)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:148)
      at android.app.ActivityThread.main(ActivityThread.java:5441)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

数据库 onCreate 调用:

@Override
public void onCreate(SQLiteDatabase db) {

    // Create Statements
    String CREATE_TABLE_LOG_TIME = "CREATE TABLE " + TABLE_LOG_TIME + " " +
            "(" +
            KEY_LOG_TIME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            KEY_LOG_TIME_TIME + " DATETIME DEFAULT CURRENT_TIMESTAMP" +
            ")";

    // Execute statements
    db.execSQL(CREATE_TABLE_LOG_TIME);

}

所有值都是 default/auto_increment 个值。

如何在此 table 中插入记录?

要插入具有默认值的行,请指定至少一列具有空值:

ContentValues cv = new ContentValues();
cv.putNull(KEY_LOG_TIME_TIME);
db.insert(TABLE_LOG_TIME, null, cv);

替换这个

db.insert(TABLE_LOG_TIME, null, new ContentValues());

db.insert(TABLE_LOG_TIME, null, null);