sqlite实例教程:iOS用sqlite打造词典
sqlite是个好东西,对于移动平台来说。一直想写有关sqlite的教程,但是不知道从何写起,考虑了很久,还是从一个小Demo 谈起吧。我写了一个精简版的词典,实现了增删查改的基本功能。
工程结构如下
最后效果图如下
效果图中可以看到,我查询 "cc",所有相关条目都查询出来了。
好了,现在开始讲解我的项目。首先可以看我的工程目录,QueryResultList 是界面控制类,DB 是数据库操作类。
整个项目的流程:我们在search框中输入要查询的内容点击搜索,底层模糊查询返回结果显示在tableView中。
我们先从底层的操作讲起,目前我就实现了插入与查询操作,删除与修改以后再补上:
1.创建数据库
- (const char*)getFilePath{//获取数据库路径 return [[NSString stringWithFormat:@"%@/Documents/l",NSHomeDirectory() ] UTF8String]; }
// DB.h //iukey #import <Foundation/Foundation.h> #import "/usr/include/sqlite3.h" @interface DB : NSObject{ sqlite3* pdb;//数据库句柄 } @property(nonatomic,assign)sqlite3* pdb; - (BOOL)insertRecordWithEN:(NSString*)en CN:(NSString*)cn Comment:(NSString*)comment;//插入一条纪录 - (NSMutableArray*)quary:(NSString*)str;//查询 - (const char*)getFilePath;//获取数据库路径 - (BOOL)createDB;//创建数据库 - (BOOL)createTable;//创建表 [url=home.php?mod=space&uid=10695]@END[/url]
2.创建表
- (BOOL)createTable{ char* err; char* sql = "create table dictionary(ID integer primary key autoincrement,en nvarchar(64),cn nvarchar(128),comment nvarchar(256))";//创建表语句 if (sql==NULL) { return NO; } if (SQLITE_OK != sqlite3_open([self getFilePath ], &pdb)){ return NO; } if (SQLITE_OK == sqlite3_exec(pdb, sql, NULL, NULL, &err)) {//执行创建表语句成功 sqlite3_close(pdb); return YES; }else{//创建表失败 return NO; } }
3.插入一条纪录
- (BOOL)insertRecordWithEN:(NSString*)en CN:(NSString*)cn Comment:(NSString*)comment{ int ret = 0; if (SQLITE_OK != sqlite3_open([self getFilePath ], &pdb)){//打开数据库 return NO; } char* sql = "insert into dictionary(en,cn,comment) values(?,?,?);";//插入语句,3个参数 sqlite3_stmt* stmt;// if (sqlite3_prepare_v2(pdb, sql, -1, &stmt, nil)==SQLITE_OK) {//准备语句 sqlite3_bind_text(stmt, 1, [en UTF8String], -1, NULL);//绑定参数 sqlite3_bind_text(stmt, 2, [cn UTF8String], -1, NULL); sqlite3_bind_text(stmt, 3, [comment UTF8String], -1, NULL); }else{ return NO; } if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询 sqlite3_finalize(stmt); sqlite3_close(pdb); return YES; }else{ return NO; } }
4.查询
- (NSMutableArray*)quary:(NSString *)str{ NSMutableArray* arr =[[NSMutableArray alloc]init];//存放查询结果 if (SQLITE_OK != sqlite3_open([self getFilePath ], &pdb)){ return NO; } char* sql = "select * from dictionary where en like ? or cn like ? or comment like ?;";//查询语句 sqlite3_stmt* stmt; if (sqlite3_prepare_v2(pdb, sql, -1, &stmt, nil)==SQLITE_OK) {//准备 sqlite3_bind_text(stmt, 1,[[NSString stringWithFormat:@"%%%@%%",str]UTF8String], -1, NULL); sqlite3_bind_text(stmt, 2, [[NSString stringWithFormat:@"%%%@%%",str]UTF8String], -1, NULL); sqlite3_bind_text(stmt, 3, [[NSString stringWithFormat:@"%%%@%%",str]UTF8String], -1, NULL); }else{ return nil; } while( SQLITE_ROW == sqlite3_step(stmt) ){//执行 char* _en = (char*)sqlite3_column_text(stmt, 1); char* _cn = (char*)sqlite3_column_text(stmt, 2); char* _comment = (char*)sqlite3_column_text(stmt, 3); NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];//单条纪录 [dict setObject:[NSString stringWithCString:_en encoding:NSUTF8StringEncoding] forKey:@"kEN"]; [dict setObject:[NSString stringWithCString:_cn encoding:NSUTF8StringEncoding] forKey:@"kCN"]; [dict setObject:[NSString stringWithCString:_comment encoding:NSUTF8StringEncoding] forKey:@"kCOMMENT"]; [arr addObject:dict];//插入到结果数组 } sqlite3_finalize(stmt); sqlite3_close(pdb); return [arr autorelease];//返回查询结果数组 }
5.DB 初始化
我先定义了一个宏,用来标识是否是第一次运行程序,如果是第一次运行就要运行创建数据库与表的函数,否则就不运行,具体看代码:
#define FIRSTINIT 1//第一次运行则设为1,否则就是0 - (id)init{ self = [super init]; if (self!=nil) { #if FIRSTINIT [self createDB]; [self createTable]; [self insertRecordWithEN:@"cctv1" CN:@"央视1套" Comment:@"SB电视台1"];//为了方便测试我插入了一些纪录 [self insertRecordWithEN:@"cctv2" CN:@"央视2套" Comment:@"SB电视台2"]; [self insertRecordWithEN:@"cctv3" CN:@"央视3套" Comment:@"SB电视台3"]; [self insertRecordWithEN:@"cctv4" CN:@"央视4套" Comment:@"SB电视台4"]; [self insertRecordWithEN:@"cctv5" CN:@"央视5套" Comment:@"SB电视台5"]; [self insertRecordWithEN:@"cctv6" CN:@"央视6套" Comment:@"SB电视台6"]; [self insertRecordWithEN:@"cctv7" CN:@"央视7套" Comment:@"SB电视台7"]; [self insertRecordWithEN:@"cctv8" CN:@"央视8套" Comment:@"SB电视台8"]; [self insertRecordWithEN:@"cctv9" CN:@"央视9套" Comment:@"SB电视台9"]; [self insertRecordWithEN:@"cctv10" CN:@"央视10套" Comment:@"SB电视台10"]; [self insertRecordWithEN:@"cctv11" CN:@"央视11套" Comment:@"SB电视台11"]; [self insertRecordWithEN:@"cctv12" CN:@"央视12套" Comment:@"SB电视台12"]; #endif } return self; }
底层的数据库暂时就这些,接着讲上层的界面部分
// QueryResultList.h // iukey #import <UIKit/UIKit.h> #import "DB.h" @interface QueryResultList : UITableViewController<UISearchBarDelegate>{ NSMutableArray* mArr;//tableView数据源 DB* db ;//数据库对象 UISearchBar* searchBar ;//搜索框 } @property(nonatomic,retain)NSMutableArray* mArr; @property(nonatomic,retain)DB* db; @property(nonatomic,retain)UISearchBar* searchBar ; @end
- (id)initWithStyle:(UITableViewStyle)style{ self = [super initWithStyle:style]; if (self) { mArr = [[NSMutableArray alloc]init];//表数据源 db =[[DB alloc]init];//数据库控制器 searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(44.0,0,200.0,44)];//搜索控件 searchBar.delegate=self;//设置搜索控件的委托 self.navigationItem.titleView = searchBar; } return self; }
接下来我们实现表格数据源委托
#pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1;//分区数 } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return [mArr count];//行数 } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; for ( UIView* view in cell.contentView.subviews) { [view removeFromSuperview]; } if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } UILabel* lblEN = [[UILabel alloc]initWithFrame:CGRectMake(5.0, 5.0, 300.0, 30.0)];//显示英文的文字标签控件 UILabel* lblCN = [[UILabel alloc]initWithFrame:CGRectMake(5.0, 35.0, 300.0, 30.0)];//中文 UILabel* lblComment = [[UILabel alloc]initWithFrame:CGRectMake(5.0, 65.0, 300.0, 30.0)];//详细 //背景颜色清掉 lblEN.backgroundColor = [UIColor clearColor]; lblCN.backgroundColor = [UIColor clearColor]; lblComment.backgroundColor = [UIColor clearColor]; // lblEN.text = [[mArr objectAtIndex:indexPath.row] objectForKey:@"kEN"]; lblCN.text = [[mArr objectAtIndex:indexPath.row] objectForKey:@"kCN"]; lblComment.text = [[mArr objectAtIndex:indexPath.row] objectForKey:@"kCOMMENT"]; [cell.contentView addSubview:lblEN]; [cell.contentView addSubview:lblCN]; [cell.contentView addSubview:lblComment]; cell.selectionStyle = UITableViewCellSelectionStyleNone;//选中不要高亮 [lblEN release]; [lblCN release]; [lblComment release]; return cell; }
然后实现搜索委托方法:
相关推荐
DAV数据库 2020-06-17
airfling 2020-05-31
zbcaicai 2020-05-26
beibeijia 2020-04-25
Rain 2020-04-16
Plant 2020-04-08
园搬家测试账号 2020-03-25
MFCJCK 2020-02-24
xiaoxiangyu 2020-02-23
Plant 2020-02-03
CharlesYooSky 2020-02-01
MFCJCK 2020-01-31
nxcjh 2020-01-29
wintershii 2020-01-18
zbcaicai 2020-01-03
MFCJCK 2019-12-30
airfling 2019-12-28
Plant 2019-12-27
Dlanguage 2019-12-27
Dlanguage 2019-12-25
whyname 2019-12-23