设为首页 收藏本站
查看: 1242|回复: 0

[经验分享] sqlite 实例教程 IOS下用sqlite打造词典-IOS开发

[复制链接]
发表于 2016-11-29 10:10:13 | 显示全部楼层 |阅读模式
声明
欢迎转载,但是请尊重作者劳动成果,转载请保留此框内声明,谢谢。
文章出处:http://blog.csdn.net/iukey
  sqlite 是个好东西,对于移动平台来说。一直想写有关sqlite的教程,但是不知道从何写起,考虑了很久,还是从一个小Demo 谈起吧。我写了一个精简版的词典,实现了增删查改的基本功能。
  工程结构如下 DSC0000.gif 。最后效果图如下 DSC0001.gif
  效果图中可以看到,我查询 "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;//创建表@end2.创建表- (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;}然后实现搜索委托方法:#pragma mark - UISearchBar delegate- (void) searchBarSearchButtonClicked:(UISearchBar*)activeSearchbar{[mArr removeAllObjects];NSString* query= searchBar.text;NSMutableArray* arr = [db quary:query];for ( NSMutableDictionary* dict in arr) {[mArr addObject:dict];}[searchBar resignFirstResponder];[self.tableView reloadData];}基本就结束了,这只是一个简单的Demo,sqlite的基本使用方法我也会慢慢整理出来,最后附上完整工程文件:DictionaryDemo





  

  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-307091-1-1.html 上篇帖子: [转]在PHP4中安装SQLITE 下篇帖子: sqlite一些基本的操作
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表