代码之家  ›  专栏  ›  技术社区  ›  Parsa

Android SQLite可能的错误:插入日期

  •  0
  • Parsa  · 技术社区  · 10 年前

    下面是来自数据库处理程序类的一些代码,用于管理SQLitedatabase表。日期插入为04082015,但输出为40082015,如果日期大于10,则不会出现此错误。

    我正在创建如下表

    @Override
    public void onCreate(SQLiteDatabase db) {
            String create_college_table = "CREATE TABLE " + TableName + " (" +
                    "  `"+KEY_ID+"` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
                    "  `"+KEY_DATE+"` DATETIME NOT NULL UNIQUE,\n" +
                    "  `"+KEY_JSON+"` longtext NOT NULL\n" +
                    ")";
            db.execSQL(create_college_table);
    }
    

    现在,在上表中插入一行:

    public void testit() {
        // write the row into the database:
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues insertValues = new ContentValues();
        // DATE IS FOURTH OF AUGUST 2015
        insertValues.put(KEY_DATE, "04082015");
        insertValues.put(KEY_JSON, "{test}");
        db.insert(
                TableName,
                null,
                insertValues
        );
    
    
        // Now read from the database, select the row that was
        // just inserted
        String selectQuery = "SELECT * FROM " + TableName + " " +
                "WHERE " + KEY_JSON + " = '{test}'";
        SQLiteDatabase db_read = this.getWritableDatabase();
        Cursor cursor = db_read.rawQuery(selectQuery, null);
        // Viewing the log the inserted date (04082015) has been
        // outputted as 40082015, this does not occur with dates
        // were the day in the month is ten or larger?!
        Log.e("testMethod", DatabaseUtils.dumpCursorToString(cursor));
    }
    
    1 回复  |  直到 10 年前
        1
  •  4
  •   Rami Jarrar    10 年前

    sqlite中的日期格式应为以下格式:

    YYYY-MM-DD
    YYYY-MM-DD HH:MM
    YYYY-MM-DD HH:MM:SS
    YYYY-MM-DD HH:MM:SS.SSS
    YYYY-MM-DDTHH:MM
    YYYY-MM-DDTHH:MM:SS
    YYYY-MM-DDTHH:MM:SS.SSS
    HH:MM
    HH:MM:SS
    HH:MM:SS.SSS
    now
    DDDDDDDDDD 
    

    有关详细信息,请查看: http://www.sqlite.org/lang_datefunc.html