iOS中用到的数据库是 SQLite,首先我们需要导入 libsqlite3.tbd (新版的包名都是这),导入头文件 #import
然后根据系统提供的函数去进行数据库的操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
NSString *sqlPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"sqlite"]; //数据库路径使用UTF8编码 const char *cfile = sqlPath.UTF8String; sqlite3 *db; //打开数据库的结果 int result = sqlite3_open(cfile, &db); if (result == SQLITE_OK) { NSLog(@"成功打开数据库!"); //创建数据表的SQL const char *sql = "CREATE TABLE IF NOT EXISTS test(id integer PRIMARY KEY AUTOINCREMENT,name text NOT NULL,age integer NOT NULL);"; //错误信息 char *errormsg = NULL; result = sqlite3_exec(db, sql, NULL, NULL, &errormsg); if (result == SQLITE_OK) { NSLog(@"创建表成功!"); }else{ NSLog(@"创建表失败 ----%s",errormsg); } }else{ NSLog(@"打开数据库失败!"); } // 增 for (int i = 0; i < 20; i++) { NSString *name = [NSString stringWithFormat:@"我是大神-%d",i]; int age = arc4random_uniform(20)+10; //数据库插入语句 NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO test (name,age) VALUES ('%@',%d);",name,age]; //错误信息 char *errmsg = NULL; result = sqlite3_exec(db, insertSql.UTF8String, nil, nil, &errmsg); if (result == SQLITE_OK) { NSLog(@"插入成功!"); }else{ NSLog(@"插入失败!"); } } // 查 const char *selectSql="SELECT id,name,age FROM test WHERE age<20;"; sqlite3_stmt *stmt=NULL; //进行查询前的准备工作 if (sqlite3_prepare_v2(db, selectSql, -1, &stmt, NULL)==SQLITE_OK) {//SQL语句没有问题 NSLog(@"查询语句没有问题"); //每调用一次sqlite3_step函数,stmt就会指向下一条记录 while (sqlite3_step(stmt)==SQLITE_ROW) {//找到一条记录 //取出数据 //(1)取出第0列字段的值(int类型的值) int ID=sqlite3_column_int(stmt, 0); //(2)取出第1列字段的值(text类型的值) const unsigned char *name=sqlite3_column_text(stmt, 1); //(3)取出第2列字段的值(int类型的值) int age=sqlite3_column_int(stmt, 2); // NSLog(@"%d %s %d",ID,name,age); printf("%d %s %d\n",ID,name,age); } }else{ NSLog(@"查询语句有问题"); } |
这就是iOS中数据库的基本操作~
代码请查看 http://git.oschina.net/zcb1603999/LearningiOS
转载请注明:怼码人生 » iOS学习笔记(二十四)————数据库操作