2012年10月7日

iOS -- sqlite3 的使用順序 & query 例子



使用 sqlite3 的一般步驟:


sqlite3_open()        Open the database  打開資料庫
sqlite3_prepare()     Create the SQL statement  準備建立好的資料庫指令 (query)
sqlite3_step()        Execute the statement  執行指令
sqlite3_column()      Fetch the result  取得結果
sqlite3_finalize()    Destroy the statement  銷燬指令
sqlite3_close()       Close the database  關閉資料庫


query 例子:
1. CREATE  TABLE "main"."STARS" ("Rowid" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "Star" VARCHAR, "image" BLOB)


2. SELECT DISTINCT [column_name] FROM [table_name];

3. SELECT * FROM * WHERE * LIKE %$value%;

4. 找幾筆資料 (no. of rows in the table):
NSString *query = [NSString stringWithFormat:@"SELECT COUNT(%@) FROM %@ ", kSelectedColumn, kTablename];
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(database, [query UTF8String] , -1, &stmt, nil) == SQLITE_OK) {
     
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            int noOfRows = (int) sqlite3_column_int(stmt, 0);
            NSLog(@"%d", noOfRows);
        }
        sqlite3_finalize(stmt2);
    } else NSLog(@"never entered!!!");
    sqlite3_close(database);



Fetch 的例子:

int sqlite3_column_count(sqlite3_stmt *pStmt);


可參考:http://www.sqlite.org/capi3ref.html

沒有留言:

張貼留言