找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 4277|回复: 0

sqlite 实例教程 IOS下用sqlite打造词典

[复制链接]
发表于 2012-3-5 11:12:59 | 显示全部楼层 |阅读模式
sqlite 是个好东西,对于移动平台来说。一直想写有关sqlite的教程,但是不知道从何写起,考虑了很久,还是从一个小Demo 谈起吧。我写了一个精简版的词典,实现了增删查改的基本功能。
工程结构如下:




最后效果图如下:

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








作者:iukey 发表于2012-3-4 22:35:53 原文链接

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?用户注册

×
您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-4-24 03:03 , Processed in 0.014155 second(s), 7 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

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