1. 程式人生 > >iOS資料庫操作

iOS資料庫操作

iOS的資料庫是sqlite3,是模糊型別的資料庫,但是仍然不能隨便定義資料型別
* 使用時首先匯入資料庫包,然後宣告資料庫變數:sqlite3 *db;
* 開啟資料庫:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *database_path = [documents stringByAppendingPathComponent:dbName];

if (sqlite3_open([database_path UTF8String], &db) != SQLITE_OK) {
    sqlite3_close(db);
    NSLog(@"資料庫開啟失敗");
}

* 建表並插入資料:
NSString *sqlCreateTable = @”CREATE TABLE IF NOT EXISTS USERS2 (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, sex TEXT,password TEXT,phone TEXT, location TEXT)”;
[self execSql:sqlCreateTable];
char *update = “INSERT OR REPLACE INTO USERS2(name,sex,password,phone,location)”“VALUES(?,?,?,?,?);”;

            char *errorMsg = NULL;
            sqlite3_stmt *stmt;

            if (sqlite3_prepare_v2(db, update, -1, &stmt, nil) == SQLITE_OK) {

                //【插入資料】在這裡我們使用繫結資料的方法,引數一:sqlite3_stmt,引數二:插入列號,引數三:插入的資料,引數四:資料長度(-1代表全部),引數五:是否需要回調
                sqlite3_bind_text(stmt, 1, [userNameText.text UTF8String], -1, NULL);
                sqlite3_bind_text(stmt, 2, [xingBei UTF8String], -1, NULL);
                sqlite3_bind_text(stmt, 3, [passText.text UTF8String], -1, NULL);
                sqlite3_bind_text(stmt, 4, [phoneText.text UTF8String], -1, NULL);
                sqlite3_bind_text(stmt, 5, [diZhiText.text UTF8String], -1, NULL);

            }
            NSLog(@"yuyuyuyuyyyyyyyyyyyyyyyyyyyyyy");
            if (sqlite3_step(stmt) != SQLITE_DONE)
                NSLog(@"資料更新失敗");

            }

* 查詢內容:
NSString sqlQuery = @”SELECT FROM USERS2”;
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {

    while (sqlite3_step(statement) == SQLITE_ROW) {

        char *name = (char*)sqlite3_column_text(statement, 1);
        NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];

        char *password=(char*)sqlite3_column_text(statement, 3);
        NSString *nsPasswordStr=[[NSString alloc]initWithUTF8String:password];

         NSLog(@"name:%@     password:%@ ",nsNameStr,nsPasswordStr);

    }

}

* 刪除內容:
NSString *sqlQuery2 = @”DELETE FROM USERS2 WHERE name =’Wx’ “;
if (sqlite3_prepare_v2(db, [sqlQuery2 UTF8String], -1, &statement, nil) == SQLITE_OK) {

                while (sqlite3_step(statement) == SQLITE_ROW) {


                }
            }