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

来源:互联网 发布:shopex源码下载 编辑:程序博客网 时间:2024/05/16 02:06

声明
欢迎转载,但是请尊重作者劳动成果,转载请保留此框内声明,谢谢。
文章出处:http://blog.csdn.net/iukey

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;//创建表@end
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;}
然后实现搜索委托方法:
#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







原创粉丝点击