使用Sqlite查询
打开一个终端,执行命令 sqlite3 student.sqlite
如果提示符为 sqlite> 表示进入sqlite3成功
执行 .help 查看帮助,执行 .exit 退出
执行命令创建表student
CREATE TABLE student(id INTEGER PRIMARY KEY, name VARCHAR(25), age INTEGER);
插入若干数据
INSERT INTO student(name,age) VALUES('张三',29); INSERT INTO student(name,age) VALUES('李四',30); INSERT INTO student(name,age) VALUES('王五',28); INSERT INTO student(name,age) VALUES('赵六',25);
在用户目录下找到文件student.sqlite,将其添加至app下
添加时选中Copy items into destination group's folder
为了使用sqlite3库函数,在Frameworks中添加 libsqlite3.0.dylib 引用
源代码中添加头函数引用 #import <sqlite3.h>
添加代码,代码可以放在viewDidLoad中
//得到数据文件路径 NSString *path = [[NSBundle mainBundle] pathForResource:@"student" ofType:@"sqlite"]; NSLog(@"db file path: %@", path); //打开数据文件 sqlite3* database; if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) { NSLog(@"open database successfully"); } else { sqlite3_close(database); NSLog(@"Failed to open databse: '%s", sqlite3_errmsg(database)); return; } //执行查询 const char* sql = "SELECT * from student"; sqlite3_stmt *statement; if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) { //遍历数据 while (sqlite3_step(statement) == SQLITE_ROW) { NSLog(@"id: %d, name: %@ ,age: %d", sqlite3_column_int(statement, 0), [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)], sqlite3_column_int(statement, 2) ); } } //关闭数据文件 sqlite3_close(database);