sqlite實(shí)例教程:iOS用sqlite打造詞典
sqlite是個(gè)好東西,對(duì)于移動(dòng)平臺(tái)來說。一直想寫有關(guān)sqlite的教程,但是不知道從何寫起,考慮了很久,還是從一個(gè)小Demo 談起吧。我寫了一個(gè)精簡版的詞典,實(shí)現(xiàn)了增刪查改的基本功能。
工程結(jié)構(gòu)如下
最后效果圖如下
效果圖中可以看到,我查詢 "cc",所有相關(guān)條目都查詢出來了。
好了,現(xiàn)在開始講解我的項(xiàng)目。首先可以看我的工程目錄,QueryResultList 是界面控制類,DB 是數(shù)據(jù)庫操作類。
整個(gè)項(xiàng)目的流程:我們?cè)趕earch框中輸入要查詢的內(nèi)容點(diǎn)擊搜索,底層模糊查詢返回結(jié)果顯示在tableView中。
我們先從底層的操作講起,目前我就實(shí)現(xiàn)了插入與查詢操作,刪除與修改以后再補(bǔ)上:
1.創(chuàng)建數(shù)據(jù)庫
- - (const char*)getFilePath{//獲取數(shù)據(jù)庫路徑
- return [[NSString stringWithFormat:@"%@/Documents/l",NSHomeDirectory() ] UTF8String];
- }
- // DB.h
- //iukey
- #import <Foundation/Foundation.h>
- #import "/usr/include/sqlite3.h"
- @interface DB : NSObject{
- sqlite3* pdb;//數(shù)據(jù)庫句柄
- }
- @property(nonatomic,assign)sqlite3* pdb;
- - (BOOL)insertRecordWithEN:(NSString*)en CN:(NSString*)cn Comment:(NSString*)comment;//插入一條紀(jì)錄
- - (NSMutableArray*)quary:(NSString*)str;//查詢
- - (const char*)getFilePath;//獲取數(shù)據(jù)庫路徑
- - (BOOL)createDB;//創(chuàng)建數(shù)據(jù)庫
- - (BOOL)createTable;//創(chuàng)建表
- [url=home.php?mod=space&uid=10695]@END[/url]
2.創(chuàng)建表
- - (BOOL)createTable{
- char* err;
- char* sql = "create table dictionary(ID integer primary key autoincrement,en nvarchar(64),cn nvarchar(128),comment nvarchar(256))";//創(chuàng)建表語句
- 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)) {//執(zhí)行創(chuàng)建表語句成功
- sqlite3_close(pdb);
- return YES;
- }else{//創(chuàng)建表失敗
- return NO;
- }
- }
3.插入一條紀(jì)錄
- - (BOOL)insertRecordWithEN:(NSString*)en CN:(NSString*)cn Comment:(NSString*)comment{
- int ret = 0;
- if (SQLITE_OK != sqlite3_open([self getFilePath ], &pdb)){//打開數(shù)據(jù)庫
- return NO;
- }
- char* sql = "insert into dictionary(en,cn,comment) values(?,?,?);";//插入語句,3個(gè)參數(shù)
- sqlite3_stmt* stmt;//
- if (sqlite3_prepare_v2(pdb, sql, -1, &stmt, nil)==SQLITE_OK) {//準(zhǔn)備語句
- sqlite3_bind_text(stmt, 1, [en UTF8String], -1, NULL);//綁定參數(shù)
- 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))) {//執(zhí)行查詢
- sqlite3_finalize(stmt);
- sqlite3_close(pdb);
- return YES;
- }else{
- return NO;
- }
- }
4.查詢
- - (NSMutableArray*)quary:(NSString *)str{
- NSMutableArray* arr =[[NSMutableArray alloc]init];//存放查詢結(jié)果
- 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) {//準(zhǔn)備
- 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) ){//執(zhí)行
- 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];//單條紀(jì)錄
- [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];//插入到結(jié)果數(shù)組
- }
- sqlite3_finalize(stmt);
- sqlite3_close(pdb);
- return [arr autorelease];//返回查詢結(jié)果數(shù)組
- }
5.DB 初始化
我先定義了一個(gè)宏,用來標(biāo)識(shí)是否是第一次運(yùn)行程序,如果是第一次運(yùn)行就要運(yùn)行創(chuàng)建數(shù)據(jù)庫與表的函數(shù),否則就不運(yùn)行,具體看代碼:
- #define FIRSTINIT 1//第一次運(yùn)行則設(shè)為1,否則就是0
- - (id)init{
- self = [super init];
- if (self!=nil) {
- #if FIRSTINIT
- [self createDB];
- [self createTable];
- [self insertRecordWithEN:@"cctv1" CN:@"央視1套" Comment:@"SB電視臺(tái)1"];//為了方便測(cè)試我插入了一些紀(jì)錄
- [self insertRecordWithEN:@"cctv2" CN:@"央視2套" Comment:@"SB電視臺(tái)2"];
- [self insertRecordWithEN:@"cctv3" CN:@"央視3套" Comment:@"SB電視臺(tái)3"];
- [self insertRecordWithEN:@"cctv4" CN:@"央視4套" Comment:@"SB電視臺(tái)4"];
- [self insertRecordWithEN:@"cctv5" CN:@"央視5套" Comment:@"SB電視臺(tái)5"];
- [self insertRecordWithEN:@"cctv6" CN:@"央視6套" Comment:@"SB電視臺(tái)6"];
- [self insertRecordWithEN:@"cctv7" CN:@"央視7套" Comment:@"SB電視臺(tái)7"];
- [self insertRecordWithEN:@"cctv8" CN:@"央視8套" Comment:@"SB電視臺(tái)8"];
- [self insertRecordWithEN:@"cctv9" CN:@"央視9套" Comment:@"SB電視臺(tái)9"];
- [self insertRecordWithEN:@"cctv10" CN:@"央視10套" Comment:@"SB電視臺(tái)10"];
- [self insertRecordWithEN:@"cctv11" CN:@"央視11套" Comment:@"SB電視臺(tái)11"];
- [self insertRecordWithEN:@"cctv12" CN:@"央視12套" Comment:@"SB電視臺(tái)12"];
- #endif
- }
- return self;
- }
底層的數(shù)據(jù)庫暫時(shí)就這些,接著講上層的界面部分
- // QueryResultList.h
- // iukey
- #import <UIKit/UIKit.h>
- #import "DB.h"
- @interface QueryResultList : UITableViewController<UISearchBarDelegate>{
- NSMutableArray* mArr;//tableView數(shù)據(jù)源
- DB* db ;//數(shù)據(jù)庫對(duì)象
- 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];//表數(shù)據(jù)源
- db =[[DB alloc]init];//數(shù)據(jù)庫控制器
- searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(44.0,0,200.0,44)];//搜索控件
- searchBar.delegate=self;//設(shè)置搜索控件的委托
- self.navigationItem.titleView = searchBar;
- }
- return self;
- }
接下來我們實(shí)現(xiàn)表格數(shù)據(jù)源委托
- #pragma mark - Table view data source
- - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
- return 1;//分區(qū)數(shù)
- }
- - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
- return [mArr count];//行數(shù)
- }
- - (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)];//顯示英文的文字標(biāo)簽控件
- 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)];//詳細(xì)
- //背景顏色清掉
- 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;
- }
然后實(shí)現(xiàn)搜索委托方法:
- #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];
- }
基本就結(jié)束了,這只是一個(gè)簡單的Demo,sqlite的基本使用方法我也會(huì)慢慢整理出來。