顯示具有 SQLite 標籤的文章。 顯示所有文章
顯示具有 SQLite 標籤的文章。 顯示所有文章

2015年5月18日 星期一

SQLite using rawQuery

目的:

在android中使用SQLiteDatabase.rawQuery( query, whereArgs ) 進行query。

操作:

            String query = "SELECT r.id FROM %s c INNER JOIN %s r ON c.name = r.name WHERE c.id = ?" ;
            query = String.format( query, src_table_name, change_table_name, 0 ) ;
            String[] whereArgs = new String[] { String.valueOf( id ) } ;
            Cursor c = db.rawQuery( query, whereArgs ) ;

Q1. 「?」使用在table name位置時,android 會出現SQLException,無法執行。

A1. 使用String.format,搭配「%s」方式導入table name,但其他條件仍使用whereArgs方式,在query時帶入。

2015年5月17日 星期日

SQLite 時間

目的:

在SQLite中insert時,default值填入current time。

操作:

CREATE TABLE IF NOT EXISTS `test` (
  `curr_time` TIMESTAMP DEFAULT (datetime('now','localtime')) -- 時間
)

  1. `curr_time` TIMESTAMP DEFAULT (datetime('now','localtime')) :目前手機時間
  2. `curr_time` TIMESTAMP DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')) :目前手機時間
  3. `curr_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP :時間有可能非手機目前的時間

insert時間:

in Android:

            ContentValues contentValues = new ContentValues() ;
            contentValues.put( "curr_time", new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).format( new Date() ) ) ;
            success = ( db.update( "test", contentValues, null, null ) > 0 ) ;