iOS SQLite的使用

来源:互联网 发布:垃圾食品税收 知乎 编辑:程序博客网 时间:2024/06/07 07:06

1.添加SQLite的框架


2.打开数据库

- (void)viewDidLoad{    [super viewDidLoad];// 打开数据库    [self openDB];                                                                                                               <span style="font-family: Arial, Helvetica, sans-serif;">}</span>

- (void)openDB{    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    NSString *path = [doc stringByAppendingPathComponent:@"student.db"];    int result = sqlite3_open(path.UTF8String, &_db);    if (result == SQLITE_OK) {        NSLog(@"打开数据库成功");        const char *sql = "create table if not exists t_student (id integer primary key autoincrement,name text,age integer);";        char *error = NULL;        int result = sqlite3_exec(_db, sql, NULL, NULL, &error);        if (result == SQLITE_OK) {            NSLog(@"成功创表");                    }else{            NSLog(@"创表失败,原因:%s",error);        }            }else{        NSLog(@"打开数据库失败");    }}
3.数据库操作

3.1插入

- (IBAction)insert {    const char *sql = "insert into t_student (name, age) values('zhangsan', '23');";    char *error = NULL;    int result = sqlite3_exec(_db, sql, NULL, NULL, &error);    if (result == SQLITE_OK) {        NSLog(@"成功新增数据");    }else{        NSLog(@"新增数据失败,原因:%s",error);    }}


3.2更新

- (IBAction)update {    const char *sql = "UPDATE t_student SET name = 'lisi' ";    char *error = NULL;    int result = sqlite3_exec(_db, sql, NULL, NULL, &error);    if (result == SQLITE_OK) {        NSLog(@"成功更新数据");    }else{        NSLog(@"更新数据失败,原因:%s",error);    }}

3.3删除

- (IBAction)delete {    const char *sql = "delete  from  t_student";    char *error = NULL;    int result = sqlite3_exec(_db, sql, NULL, NULL, &error);    if (result == SQLITE_OK) {        NSLog(@"成功删除数据");    }else{        NSLog(@"删除失败,原因:%s",error);    }}

3.4查询

- (IBAction)query {    const char *sql = "select *   from  t_student1 where name = ?;";    sqlite3_stmt *stmt = NULL; // 初始化结果集    int result = sqlite3_prepare(_db, sql, -1, &stmt, NULL); // 检查查询语句是否合法        if (result == SQLITE_OK) {        NSLog(@"查询语句合法");        // 设置占位符内容        sqlite3_bind_text(stmt, 1, "lisi" , -1,NULL);                while (sqlite3_step(stmt) == SQLITE_ROW) { // 真的查询到一行数据            // 获得这行对应的数据                        // 获得第0列的id            int sid = sqlite3_column_int(stmt, 0);                        // 获得第1列的name            const unsigned char *sname = sqlite3_column_text(stmt, 1);                        // 获得第2列的age            int sage = sqlite3_column_int(stmt, 2);                        NSLog(@"%d %s %d", sid, sname, sage);        }            }else{        NSLog(@"查询语句不合法");    }}




0 0
原创粉丝点击