> 数据库 > SQLite >

Ios开发之sqlite

Sqlite是ios数据存储的一个重要手段,今天我们就一块来看一下,怎样使用sqlite将数据存储到沙盒中去。

第一步:导入一个框架libsqlite3.0.dylib

选中TARGETS在General中的Linked Frameworks and Libraries选项中点击‘+’添加

第二步:代码部分

1.找到沙盒中的路径

NSArray *path =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [path objectAtIndex:0];
 NSString *dbPath = [documentPath stringByAppendingPathComponent:@"sqlite.db"];

2.创建sqlite对象,并执行打开操作

sqlite3 *db;
    //打开数据库
int res = sqlite3_open(dbPath.UTF8String, &db);

3.创建表

NSString *sql = @"create table if not exists 'student' ('id' integer primary key autoincrement,'studentname' varchar)";
int sqlRes = sqlite3_exec(db, sql.UTF8String, NULL, NULL, NULL);
 if (sqlRes == SQLITE_OK) {
     NSLog(@"create table ok");
 }

4.向表中插入数据

//增 NSString *sql1 = @"insert into student (studentname) values ('小帐')";
int sql1Res = sqlite3_exec(db, sql1.UTF8String, NULL, NULL, NULL);
if (sql1Res == SQLITE_OK) {
    NSLog(@"insert ok");
}

5.从表中删除数据

NSString *deletesql  = @"delete from student where id = 3";
int deleres = sqlite3_exec(db, deletesql.UTF8String, NULL, NULL, NULL);
if (deleres == SQLITE_OK) {
     NSLog(@"delete is ok");
}

6.修改表中的数据

//修改
NSString *updateSql = @"update student set studentname = 'wangling' where id = 4";
int updateres = sqlite3_exec(db, updateSql.UTF8String, NULL, NULL, NULL);
if (updateres == SQLITE_OK) {
      NSLog(@"update is ok");
}

7.查询数据

查询数据和,增删改都有所不同,我们需要首先创建sqlite_stmt对象,用来存放我们查询的数据流(二进制),然后使用sqlite3_prepare_v2函数准备,通过sqlite3_bind_添加查询参数最后获取数据,最后关闭sqlite_stmt对象。

//查
        sqlite3_stmt *stmt;
        NSString *selectSql = @"select * from student where id = ?";

        if (sqlite3_prepare_v2(db, selectSql.UTF8String, -1, &stmt, nil) == SQLITE_OK) {
            sqlite3_bind_int(stmt, 1, 4);
            while (sqlite3_step(stmt) == SQLITE_ROW) {
                int identity = sqlite3_column_int(stmt, 0);
                NSLog(@"%d",identity);
                char * name= (char *)sqlite3_column_text(stmt, 1);
                NSLog(@"%@",[NSString stringWithUTF8String:name]);
            }
            if (stmt) {
                sqlite3_finalize(stmt);
}

8.关闭数据库sqlite对象

if (db) {
        sqlite3_close(db);
    }


(责任编辑:IT)