iOS数据库操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33351713/article/details/76358908

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) {


                }
            }

猜你喜欢

转载自blog.csdn.net/qq_33351713/article/details/76358908