iOS Sqlite的详解
2016-04-26 14:27
405 查看
1.创建数据库
//创建数据库路径 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"Person.sqlite"]; NSLog(@"Path: %@", path); //打开上面的创建的数据库,如果不存在,则会创建 //路径转为统一格式 const char *filename = [path cStringUsingEncoding:NSUTF8StringEncoding]; //#import <sqlite3.h> 以及 添加 libsqlite3.0.tbd sqlite3 *ppDb = NULL; int response = sqlite3_open(filename, &ppDb); if (response == SQLITE_OK) { NSLog(@"打开Person.sqlite数据库成功"); }else NSLog(@"打开Person.sqlite数据库失败");
2.创建表格
//创建表table,这个要熟悉数据库的建表语句,这个了解一下即可 const char *creatTable = "create table if not exists Student(name varchar, age integer, sex varchar, class integer, school varchar, address varchar, studentID varchar primary key)"; //表创建失败 table Student already exists char *error = NULL; response = sqlite3_exec(ppDb, creatTable, NULL, NULL, &error); if (response == SQLITE_OK) { NSLog(@"创建表成功"); }else{ NSLog(@"表创建失败 %s", error); }
3.插入以及更新记录
//插入一条记录 const char *insertSql = "insert into Student values ('YaoMing', 30, 'Male', 'SofeWare 1', 'SofeWare', '广州上下九步行街', '20095531011')"; response = sqlite3_exec(ppDb, insertSql, NULL, NULL, &error); if (response == SQLITE_OK) { NSLog(@"插入成功"); }else{ NSLog(@"插入失败 %s", error); } //update 记录 const char *updateSchool = "update Student set school = '广州大学'"; response = sqlite3_exec(ppDb, updateSchool, NULL, NULL, &error); if (response == SQLITE_OK) { NSLog(@"update successful"); }else NSLog(@"update failed: %s", error);
4.删除行
//删除 记录 const char *delete = "delete from Student"; response = sqlite3_exec(ppDb, delete, NULL, NULL, &error); if (response == SQLITE_OK) { NSLog(@"delete 成功"); }else NSLog(@"删除失败 %s", error);
5.查询存储的数据
//查询所有的数据 const char *querySql = "select * from Student"; //用于存储查询出来的数据 sqlite3_stmt *ppStmt = NULL; response = sqlite3_prepare_v2(ppDb, querySql, -1, &ppStmt, NULL); //遍历列表中的每一条数据,拿到其中的内容 while (sqlite3_step(ppStmt) == SQLITE_ROW) { //拿到数据中第0列的内容 const unsigned char *name = sqlite3_column_text(ppStmt, 0); //第1列的内容 const unsigned char *age = sqlite3_column_text(ppStmt, 1); NSLog(@"%s", name); NSLog(@"%s", age); // NSString *nameStr = [NSString stringWithUTF8String:name]; // NSLog(@"%@", nameStr);
6.drop 表
//drop table const char *dropTable = "drop table Student"; response = sqlite3_exec(ppDb, dropTable, NULL, NULL, &error); if (response == SQLITE_OK) { NSLog(@"drop 成功"); }else NSLog(@"drop失败 %s", error);
7.最后一点:
操作完毕后,关闭数据库,有开必有关sqlite3_close(ppDb);
相关文章推荐
- Android之获取手机上的图片和视频缩略图thumbnails
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 数据库链接字符串查询网站
- 不可修补的 iOS 漏洞可能导致 iPhone 4s 到 iPhone X 永久越狱
- iOS 12.4 系统遭黑客破解,漏洞危及数百万用户
- 每日安全资讯:NSO,一家专业入侵 iPhone 的神秘公司
- DB2实例管理
- DB2实例管理
- [转][源代码]Comex公布JailbreakMe 3.0源代码
- 保障MySQL数据安全的14个最佳方法
- mysql问答汇集
- 第三章 数据库备份和还原
- 创建一个空的IBM DB2 ECO数据库的方法
- Access 2000 数据库 80 万记录通用快速分页类
- 开通一个数据库失败的原因的和解决办法
- 一个简单的asp数据库操作类
- SQLite教程(十一):临时文件