| 聲明 歡迎轉載,但是請尊重作者勞動成果,轉載請保留此框內聲明,謝謝。 文章出處: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