sqlite项目详解
iOS开发数据库篇—SQLite的应用 一、简单说明 在iOS中使用SQLite3,首先要添加库文件libsqlite3.dylib和导入主头文件。
导入头文件,可以使用库中的函数(是纯C语言的) 二、具体说明 新建一个项目,在项目的主界面中放四个按钮(分别是,增加、删除、修改、查询)。 1.sqlite3_open(<#const char *filename#>,<#sqlite3 **ppDb#>)函数的一些说明: (1)作用:把一个文件名称传递给他,它会自动检测这个文件是否存在,如果不存在的话,会自动创建相应的文件(这里为数据库文件,刚创建为空)。 (2)参数:它的第一个参数为文件的名称(需转换为C语言的),第二个参数是数据库的实例,sqlite3 *db; 说明:sqlite3是一种类型,db是数据库的句柄,就是数据库的象征,如果要进行增删改查,就得操作db这个实例。 (3)返回值:它的返回值为int型的,根据函数的返回值可以知道,打开数据库文件是成功还是失败,如果返回值是SQLITE_OK则说明成功,否则为失败。 2.打开数据库 实现代码和显示: 查看沙盒内创建的数据库文件:
双击打开,查看发现打开的数据库连接名称为students,默认为文件名的前缀,数据库创建成功。
3.创建表 函数说明: 参数:第一个参数为数据库的句柄(db),第二个参数为sql语句,第三个参数为回调参数,是一个指向函数的指针,如果把callback前面的*改成^则就是一个block代码段,第四个参数可以写NULL,第五个参数为错误信息,用以代码调试。 1 //1.打开数据库文件(如果数据库文件不存在,那么该函数会自动创建数据库文件)
2 int result = sqlite3_open(cfileName,&db); 3 if (result==SQLITE_OK) { 打开成功
4 NSLog(@"成功打开数据库"); 5
6 2.创建表
7 const char *sql="CREATE TABLE IF NOT EXISTS t_students (id integer PRIMARY KEY AUTOINCREMENT,name text NOT NULL,age integer NOT NULL);"; 8 char *errmsg=NULL; 9 result = sqlite3_exec(db,sql,NULL,&errmsg); 10 if (result==SQLITE_OK) { 11 NSLog(创表成功12 }else
13 { 14 NSLog(创表失败----%s",errmsg); 15 } 16 }17 { 18 NSLog(打开数据库失败19 }
执行后,创表成功,打开创建的表查看: 调试技巧: 1 2 NSLog(3 }4 { 5 NSLog(@"创表失败----%s",errmsg); 6 printf(创表失败---%s----%s---%d7 } __FILE__宏打印文件名,__LINE__宏打印行号。 4.插入数据 实现代码: 1 - (IBAction)insert { for (int i=0; i<20; i++) { 3 1.拼接SQL语句 4 NSString *name=[NSString stringWithFormat:文晓--%d",arc4random_uniform(100)]; 5 int age=arc4random_uniform(20)+10; 6 NSString *sql=[NSString stringWithFormat:INSERT INTO t_students (name,age) VALUES ('%@',%d); 7 2.执行SQL语句 9 10 sqlite3_exec(self.db,sql.UTF8String,128); line-height:1.5!important">11 if (errmsg) {如果有错误信息 12 NSLog(插入数据失败--%s13 }14 { 15 NSLog(插入数据成功16 } 17 } 18 } 打印查看:查看数据库里t_students表中的数据: 5.选择(select)查询操作 select操作也可以使用sqlite3_exec函数实现,但通常使用下面的函数。 参数:第一个参数为数据库的句柄,第二个参数为sql语句,第三个参数为sql的长度(如果设置为-1,则代表系统会自动计算sql语句的长度),第四个参数用来取数据,第五个参数为尾部一般用不上可直接写NULL。 示例代码: 1 - (IBAction)select { char *sql=SELECT id,age FROM t_students WHERE age<20; 3 sqlite3_stmt *stmt=NULL; 4 5 进行查询前的准备工作 if (sqlite3_prepare_v2(self.db,-1,&stmt,NULL)==SQLITE_OK) {SQL语句没有问题 7 NSLog(查询语句没有问题 8 //每调用一次sqlite3_step函数,stmt就会指向下一条记录 while (sqlite3_step(stmt)==SQLITE_ROW) {找到一条记录 11 取出数据 12 (1)取出第0列字段的值(int类型的值) 13 int ID=sqlite3_column_int(stmt,0); 14 (2)取出第1列字段的值(text类型的值) 15 const unsigned char *name=sqlite3_column_text(stmt,128); line-height:1.5!important">1); 16 (3)取出第2列字段的值(int类型的值) 17 int age=sqlite3_column_int(stmt,128); line-height:1.5!important">2); 18 NSLog(@"%d %s %d",ID,age); 19 printf(%d %s %dn20 } 21 }22 { 23 NSLog(查询语句有问题24 } 25 26 } 打印查看查询结果:三、补充 完整代码: YYViewController.m文件 1 // 2 YYViewController.m 3 02-SQLite的应用 4 // 5 6 #import YYViewController.h" 7 #import <sqlite3.h> 8 9 @interface YYViewController () 10 db是数据库的句柄,就是数据库的象征,要对数据库进行增删改查,就得操作这个实例 11 @property(nonatomic,assign)sqlite3 *db; 12 - (IBAction)insert; 13 - (IBAction)delete; 14 - (IBAction)update; 15 - (IBAction)select; 16 17 @end 18 19 @implementation YYViewController 20 21 - (void)viewDidLoad 22 { 23 [super viewDidLoad]; 24 25 sqlite3 *db; 26 27 获得数据库文件的路径 28 NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject]; 29 NSString *fileName=[doc stringByAppendingPathComponent:students.sqlite"]; 30 将OC字符串转换为c语言的字符串 31 char *cfileName=fileName.UTF8String; 32 33 34 _db); 35 36 NSLog( 37 38 39 CREATE TABLE t_students (id integer PRIMARY KEY AUTOINCREMENT,128); line-height:1.5!important"> 40 41 result = sqlite3_exec(self.db,128); line-height:1.5!important"> 42 43 NSLog( 44 } 45 { 46 47 printf( 48 } 49 } 50 { 51 NSLog( 52 } 53 } 54 55 - (IBAction)insert { 56 57 58 NSString *name=[NSString stringWithFormat: 59 60 NSString *sql=[NSString stringWithFormat: 61 62 63 64 sqlite3_exec(self.db,128); line-height:1.5!important"> 65 66 NSLog( 67 } 68 { 69 NSLog( 70 } 71 } 72 } 73 74 - (IBAction)delete { 75 } 76 77 - (IBAction)updata { 78 } 79 80 - (IBAction)select { 81 82 sqlite3_stmt *stmt=NULL; 83 84 85 86 NSLog( 87 88 89 90 91 92 93 94 95 96 97 98 printf( 99 } 100 }101 { 102 NSLog(103 } 104 105 } 106 @endIOS开发数据库篇—SQLite模糊查询 一、示例 说明:本文简单示例了SQLite的模糊查询 1.新建一个继承自NSObject的模型
该类中的代码: YYPerson.h 03-模糊查询 5 Created by apple on 14-7-27. Copyright (c) 2014年 wendingding. All rights reserved. #import <Foundation/Foundation.h> 10 11 @interface YYPerson : NSObject 12 @property (nonatomic,assign) int ID; 13 @property (nonatomic,copy) NSString *name; 14 @property (nonatomic,255); line-height:1.5!important">intage; 15 16 @end 2.新建一个工具类,用来管理模型 工具类中的代码设计如下: YYPersonTool.h文件 YYPersonTool.h @class YYPerson; 12 @interface YYPersonTool : NSObject 13 /** 14 * 保存一个联系人 15 */ 16 + (void)save:( YYPerson*)person; 17 19 * 查询所有的联系人 20 21 + (NSArray *)query; 22 + (NSArray *)queryWithCondition:(NSString *)condition; 23 YYPersonTool.m文件 YYPersonTool.m YYPersonTool.h 10 YYPerson.h 11 12 13 @interface YYPersonTool () 14 @property(nonatomic,assign)sqlite3 *db; 15 16 @implementation YYPersonTool 17 18 static sqlite3 *_db; 首先需要有数据库 20 +(void)initialize 21 { 22 23 NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,128); line-height:1.5!important"> 24 NSString *fileName=[doc stringByAppendingPathComponent:person.sqlite 25 26 27 28 29 31 NSLog( 32 33 34 CREATE TABLE IF NOT EXISTS t_person (id integer PRIMARY KEY AUTOINCREMENT,128); line-height:1.5!important"> 35 36 37 result = sqlite3_exec(_db,128); line-height:1.5!important"> 38 39 NSLog( 40 } 41 { 42 printf(创表失败---%s 43 } 44 } 46 NSLog( 47 } 48 49 } 50 保存一条数据 51 +(void)save:(YYPerson *)person 52 { 53 55 NSString *sql=[NSString stringWithFormat:INSERT INTO t_person (name,person.name,person.age]; 56 57 58 59 sqlite3_exec(_db,128); line-height:1.5!important"> 60 61 NSLog( 62 } 63 { 64 NSLog( 65 } 66 67 } 68 69 +(NSArray *)query 70 { 71 return [self queryWithCondition:@""]; 74 模糊查询 75 +(NSArray *)queryWithCondition:(NSString *)condition 76 { 77 78 数组,用来存放所有查询到的联系人 79 NSMutableArray *persons=nil; 80 /* 81 [NSString stringWithFormat:@"SELECT id,age FROM t_person WHERE name like '%%%@%%' ORDER BY age ASC;",condition]; 82 NSString *NSsql=[NSString stringWithFormat:@"SELECT id,age FROM t_person WHERE name=%@;",128); line-height:1.5!important"> 83 */ 84 NSString *NSsql=[NSString stringWithFormat: 85 NSLog(%@ 86 char *sql=NSsql.UTF8String; 87 88 sqlite3_stmt *stmt=NULL; 89 90 91 if (sqlite3_prepare_v2(_db,128); line-height:1.5!important"> 92 NSLog( 93 94 persons=[NSMutableArray array]; 95 96 每调用一次sqlite3_step函数,stmt就会指向下一条记录 97 98 99 100 101 102 103 104 105 106 107 YYPerson *p=[[YYPerson alloc]init]; 108 p.ID=ID; 109 p.name=[NSString stringWithUTF8String:(char *)name]; 110 p.age=age; 111 NSLog(@"%@",p.name); 112 [persons addObject:p]; 113 NSLog(@"haha%@",persons); 114 } 115 }116 { 117 NSLog(118 } 119 120 NSLog(@"haha%@",128); line-height:1.5!important">121 return persons; 122 } 123 3.在storyboard中,删除原有的控制器,放一个导航控制器和UITableViewController控制器,并关联
在代码中,让主控制器直接继承自UITableViewController 代码设计如下: YYViewController.m文件 10 12 @interface YYViewController ()<UISearchBarDelegate> 14 15 添加一个数组,用来保存person 16 @property(nonatomic,strong)NSArray *persons; 17 18 20 21 #pragma mark-懒加载 22 -(NSArray *)persons 23 { 24 if (_persons==nil) { 25 _persons=[YYPersonTool query]; 26 } 27 return _persons; 28 } 29 30 1.在初始化方法中添加一个搜索框 31 - (32 { 33 [super viewDidLoad]; 34 35 设置搜索框 36 UISearchBar *search=[[UISearchBar alloc]init]; 37 search.frame=CGRectMake(0,128); line-height:1.5!important">300,128); line-height:1.5!important">44); 38 search.delegate=self; 39 self.navigationItem.titleView=search; 40 } 41 42 2.设置tableView的数据 43 设置有多少行数据 44 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 45 { 46 return 10; 47 return self.persons.count; 48 } 49 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 50 { 51 1.去缓存中取cll,若没有则自己创建并标记 52 static NSString *ID=ID53 UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID]; 54 if (cell==nil) { 55 cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID]; 56 } 57 58 2.设置每个cell的数据 59 先取出数据模型 60 YYPerson *person=self.persons[indexPath.row]; 61 设置这个cell的姓名(name)和年龄 62 cell.textLabel.text=person.name; 63 cell.detailTextLabel.text=[NSString stringWithFormat:年龄 %d64 3.返回cell 65 return cell; 66 } 67 68 - (IBAction)add:(UIBarButtonItem *)sender { 69 初始化一些假数据 70 NSArray *names = @[西门抽血西门抽筋西门抽风西门吹雪东门抽血东门抽筋东门抽风东门吹雪北门抽血北门抽筋南门抽风南门吹雪71 int i = 72 YYPerson *p = [[YYPerson alloc] init]; 73 p.name = [NSString stringWithFormat:%@-%d74 p.age = arc4random_uniform(20) + 20; 75 [YYPersonTool save:p]; 76 } 77 } 78 79 #pragma mark-搜索框的代理方法 80 -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 81 { 82 self.persons=[YYPersonTool queryWithCondition:searchText]; 83 刷新表格 84 [self.tableView reloadData]; 85 [searchBar resignFirstResponder]; 86 } 87 88 实现效果:
二、简单说明 关于:NSString*NSsql=[NSStringstringWithFormat:@"SELECT id,condition]; 注意:name like ‘西门’,相当于是name = ‘西门’。 name like ‘%西%’,为模糊搜索,搜索字符串中间包含了’西’,左边可以为任意字符串,右边可以为任意字符串,的字符串。 但是在stringWithFormat:中%是转义字符,两个%才表示一个%。 打印查看:iOS开发数据库篇—SQLite常用的函数 一、简单说明 1.打开数据库 int sqlite3_open( const char *filename,// 数据库的文件路径 sqlite3 **ppDb // 数据库实例 ); 2.执行任何SQL语句 int sqlite3_exec( sqlite3*,// 一个打开的数据库实例 const char *sql,// 需要执行的SQL语句 int (*callback)(void*,int,char**,char**),// SQL语句执行完毕后的回调 void *,// 回调函数的第1个参数 char **errmsg // 错误信息 3.检查SQL语句的合法性(查询前的准备) int sqlite3_prepare_v2( sqlite3 *db,// 数据库实例 const char *zSql,// 需要检查的SQL语句 int nByte,// SQL语句的最大字节长度 sqlite3_stmt **ppStmt,// sqlite3_stmt实例,用来获得数据库数据 const char **pzTail 4.查询一行数据 int sqlite3_step(sqlite3_stmt*); // 如果查询到一行数据,就会返回SQLITE_ROW 5.利用stmt获得某一字段的值(字段的下标从0开始) double sqlite3_column_double(sqlite3_stmt*,int iCol); // 浮点数据 int sqlite3_column_int(sqlite3_stmt*,int iCol); // 整型数据 sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*,int iCol); // 长整型数据 const void *sqlite3_column_blob(sqlite3_stmt*,int iCol); // 二进制文本数据 const unsigned char *sqlite3_column_text(sqlite3_stmt*,int iCol); // 字符串数据 二、SQLite编码 1.创建、打开、关闭数据库 创建或打开数据库 // path是数据库文件的存放路径 sqlite3*db = NULL; int result =sqlite3_open([path UTF8String],&db); 代码解析: sqlite3_open()将根据文件路径打开数据库,如果不存在,则会创建一个新的数据库。如果result等于常量SQLITE_OK,则表示成功打开数据库 sqlite3 *db:一个打开的数据库实例 数据库文件的路径必须以C字符串(而非NSString)传入 关闭数据库:sqlite3_close(db); 2.执行不返回数据的SQL语句 执行创表语句 char *errorMsg = NULL; // 用来存储错误信息 char *sql = "create table if not exists t_person(id integer primary key autoincrement,name text,age integer);"; int result =sqlite3_exec(db,&errorMsg); sqlite3_exec()可以执行任何SQL语句,比如创表、更新、插入和删除操作。但是一般不用它执行查询语句,因为它不会返回查询到的数据 sqlite3_exec()还可以执行的语句: (1)开启事务:begin transaction; (2)回滚事务:rollback; (3)提交事务:commit; 3.带占位符插入数据 char *sql = "insert into t_person(name,age) values(?,?);"; sqlite3_stmt*stmt; if (sqlite3_prepare_v2(db,-1,NULL) ==SQLITE_OK) { sqlite3_bind_text(stmt,1,"母鸡",NULL); sqlite3_bind_int(stmt,2,27); } if (sqlite3_step(stmt) !=SQLITE_DONE) { NSLog(@"插入数据错误"); sqlite3_finalize(stmt); sqlite3_prepare_v2()返回值等于SQLITE_OK,说明SQL语句已经准备成功,没有语法问题 sqlite3_bind_text():大部分绑定函数都只有3个参数 (1)第1个参数是sqlite3_stmt *类型 (2)第2个参数指占位符的位置,第一个占位符的位置是1,不是0 (3)第3个参数指占位符要绑定的值 (4)第4个参数指在第3个参数中所传递数据的长度,对于C字符串,可以传递-1代替字符串的长度 (5)第5个参数是一个可选的函数回调,一般用于在语句执行后完成内存清理工作 sqlite_step():执行SQL语句,返回SQLITE_DONE代表成功执行完毕 sqlite_finalize():销毁sqlite3_stmt *对象 4.查询数据 char *sql = "select id,age from t_person;"; while (sqlite3_step(stmt) ==SQLITE_ROW) { int _id =sqlite3_column_int(stmt,0); char *_name = (char *)sqlite3_column_text(stmt,1); NSString *name = [NSStringstringWithUTF8String:_name]; int _age =sqlite3_column_int(stmt,2); NSLog(@"id=%i,name=%@,age=%i",_id,_age); } sqlite3_finalize(stmt); sqlite3_step()返回SQLITE_ROW代表遍历到一条新记录 sqlite3_column_*()用于获取每个字段对应的值,第2个参数是字段的索引,从0开始 iOS开发数据库篇—FMDB简单介绍 一、简单说明 1.什么是FMDB FMDB是iOS平台的SQLite数据库框架 FMDB以OC的方式封装了SQLite的C语言API
2.FMDB的优点 使用起来更加面向对象,省去了很多麻烦、冗余的C语言代码 对比苹果自带的Core Data框架,更加轻量级和灵活 提供了多线程安全的数据库操作方法,有效地防止数据混乱 3.FMDB的github地址 https://github.com/ccgus/fmdb 二、核心类 FMDB有三个主要的类 (1)FMDatabase 一个FMDatabase对象就代表一个单独的SQLite数据库 用来执行SQL语句
(2)FMResultSet 使用FMDatabase执行查询后的结果集 (3)FMDatabaseQueue 用于在多线程中执行多个查询或更新,它是线程安全的 三、打开数据库 通过指定SQLite数据库文件路径来创建FMDatabase对象 FMDatabase *db = [FMDatabase databaseWithPath:path]; if (![db open]) { NSLog(@"数据库打开失败!"); } 文件路径有三种情况 (1)具体文件路径 如果不存在会自动创建 (2)空字符串@"" 会在临时目录创建一个空的数据库 当FMDatabase连接关闭时,数据库文件也被删除 (3)nil 会创建一个内存中临时数据库,当FMDatabase连接关闭时,数据库会被销毁 四、执行更新 在FMDB中,除查询以外的所有操作,都称为“更新” create、drop、insert、update、delete等 使用executeUpdate:方法执行更新 - (BOOL)executeUpdate:(NSString*)sql,... - (BOOL)executeUpdateWithFormat:(NSString*)format,255)">- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments 示例 [db executeUpdate:@"UPDATE t_student SET age = ? WHERE name = ?;",@20,@"Jack"] 五、执行查询 查询方法 - (FMResultSet *)executeQuery:(NSString*)sql,255)">- (FMResultSet *)executeQueryWithFormat:(NSString*)format,255)">- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments // 查询数据 FMResultSet *rs = [db executeQuery:@"SELECT * FROM t_student"]; // 遍历结果集 while ([rs next]) { NSString *name = [rs stringForColumn:@"name"]; int age = [rs intForColumn:@"age"]; double score = [rs doubleForColumn:@"score"]; } 六、代码示例 1.新建一个项目,导入libsqlite3库,并在项目中包含主头文件 2.下载第三方框架FMDB
3.示例代码 YYViewController.m文件 04-FMDB基本使用 FMDB.h11 13 @property(nonatomic,strong)FMDatabase *db; 18 - (19 { 20 [super viewDidLoad]; 21 1.获得数据库文件的路径 22 NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,128); line-height:1.5!important">23 NSString *fileName=[doc stringByAppendingPathComponent:student.sqlite24 25 2.获得数据库 26 FMDatabase *db=[FMDatabase databaseWithPath:fileName]; 27 28 3.打开数据库 29 if ([db open]) { 30 4.创表 31 BOOL result=[db executeUpdate:CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT,128); line-height:1.5!important">32 if (result) { 33 NSLog(34 }35 { 36 NSLog(创表失败37 } 38 } 39 self.db=db; 40 41 } 42 43 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 44 { 45 [self delete]; 46 [self insert]; 47 [self query]; 49 50 插入数据 51 -(void)insert 52 { 53 10; i++) { 54 NSString *name = [NSString stringWithFormat:jack-%d55 executeUpdate : 不确定的参数用?来占位 56 [self.db executeUpdate:INSERT INTO t_student (name,age) VALUES (?,?);40))]; 57 [self.db executeUpdate:@"INSERT INTO t_student (name,?);" withArgumentsInArray:@[name,@(arc4random_uniform(40))]]; 58 59 executeUpdateWithFormat : 不确定的参数用%@、%d等来占位 60 [self.db executeUpdateWithFormat:@"INSERT INTO t_student (name,age) VALUES (%@,%d);",arc4random_uniform(40)]; 61 } 62 } 63 64 删除数据 65 -(void)delete 66 { 67 [self.db executeUpdate:@"DELETE FROM t_student;"]; 68 [self.db executeUpdate:DROP TABLE IF EXISTS t_student;69 [self.db executeUpdate:70 } 71 72 查询 73 - (void)query 74 { 75 1.执行查询语句 76 FMResultSet *resultSet = [self.db executeQuery:SELECT * FROM t_student77 78 2.遍历结果 79 while ([resultSet next]) { 80 int ID = [resultSet intForColumn:id81 NSString *name = [resultSet stringForColumn:name82 int age = [resultSet intForColumn:age83 NSLog(%d %@ %d84 } 85 } 86 87 @end 打印查看结果: 提示: 如果ID设置为逐渐,且设置为自动增长的话,那么把表中的数据删除后,重新插入新的数据,ID的编号不是从0开始,而是接着之前的ID进行编号。 注意: 不要写成下面的形式,不要加'',直接使用%@,它会自动认为这是一个字符串。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |