複製代碼 代碼如下:
@implementation YYPersonTool
static sqlite3 *_db;
//首先需要有資料庫
+(void)initialize
{
//獲得資料庫檔案的路徑
NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName=[doc stringByAppendingPathComponent:@"person.sqlite"];
//將OC字串轉換為c語言的字串
const char *cfileName=fileName.UTF8String;
//1.開啟資料庫檔案(如果資料庫檔案不存在,那麼該函數會自動建立資料庫檔案)
int result = sqlite3_open(cfileName, &_db);
if (result==SQLITE_OK) { //開啟成功
NSLog(@"成功開啟資料庫");
//2.建立表
const char *sql="CREATE TABLE IF NOT EXISTS t_person (id integer PRIMARY KEY AUTOINCREMENT,name text NOT NULL,age integer NOT NULL);";
char *errmsg=NULL;
result = sqlite3_exec(_db, sql, NULL, NULL, &errmsg);
if (result==SQLITE_OK) {
NSLog(@"創表成功");
}else
{
printf("創表失敗---%s",errmsg);
}
}else
{
NSLog(@"開啟資料庫失敗");
}
}
//儲存一條資料
+(void)save:(YYPerson *)person
{
//1.拼接SQL語句
NSString *sql=[NSString stringWithFormat:@"INSERT INTO t_person (name,age) VALUES ('%@',%d);",person.name,person.age];
//2.執行SQL語句
char *errmsg=NULL;
sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &errmsg);
if (errmsg) {//如果有錯誤資訊
NSLog(@"插入資料失敗--%s",errmsg);
}else
{
NSLog(@"插入資料成功");
}
}
+(NSArray *)query
{
return [self queryWithCondition:@""];
}
//模糊查詢
+(NSArray *)queryWithCondition:(NSString *)condition
{
//數組,用來存放所有查詢到的連絡人
NSMutableArray *persons=nil;
/*
[NSString stringWithFormat:@"SELECT id, name, age FROM t_person WHERE name like '%%%@%%' ORDER BY age ASC;", condition];
NSString *NSsql=[NSString stringWithFormat:@"SELECT id,name,age FROM t_person WHERE name=%@;",condition];
*/
NSString *NSsql=[NSString stringWithFormat:@"SELECT id,name,age FROM t_person WHERE name like '%%%@%%' ORDER BY age ASC;",condition];
NSLog(@"%@",NSsql);
const char *sql=NSsql.UTF8String;
sqlite3_stmt *stmt=NULL;
//進行查詢前的準備工作
if (sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL)==SQLITE_OK) {//SQL語句沒有問題
NSLog(@"查詢語句沒有問題");
persons=[NSMutableArray array];
//每調用一次sqlite3_step函數,stmt就會指向下一條記錄
while (sqlite3_step(stmt)==SQLITE_ROW) {//找到一條記錄
//取出資料
//(1)取出第0欄欄位的值(int類型的值)
int ID=sqlite3_column_int(stmt, 0);
//(2)取出第1欄欄位的值(text類型的值)
const unsigned char *name=sqlite3_column_text(stmt, 1);
//(3)取出第2欄欄位的值(int類型的值)
int age=sqlite3_column_int(stmt, 2);
YYPerson *p=[[YYPerson alloc]init];
p.ID=ID;
p.name=[NSString stringWithUTF8String:(const char *)name];
p.age=age;
// NSLog(@"%@",p.name);
[persons addObject:p];
// NSLog(@"haha%@",persons);
}
}else
{
NSLog(@"查詢語句有問題");
}
//NSLog(@"haha%@",persons);
return persons;
}
@end
3.在storyboard中,刪除原有的控制器,放一個導航控制器和UITableViewController控制器,並關聯
在代碼中,讓主控制器直接繼承自UITableViewController
代碼設計如下:
YYViewController.m檔案
複製代碼 代碼如下:
//
// YYViewController.m
// 03-模糊查詢
//
// Created by apple on 14-7-27.
// Copyright (c) 2014年 wendingding. All rights reserved.
//
#import "YYViewController.h"
#import "YYPerson.h"
#import "YYPersonTool.h"
@interface YYViewController ()<UISearchBarDelegate>
//添加一個數組,用來儲存person
@property(nonatomic,strong)NSArray *persons;
@end
複製代碼 代碼如下:
@implementation YYViewController
#pragma mark-懶載入
-(NSArray *)persons
{
if (_persons==nil) {
_persons=[YYPersonTool query];
}
return _persons;
}
//1.在初始化方法中添加一個搜尋方塊
- (void)viewDidLoad
{
[super viewDidLoad];
//設定搜尋方塊
UISearchBar *search=[[UISearchBar alloc]init];
search.frame=CGRectMake(0, 0, 300, 44);
search.delegate=self;
self.navigationItem.titleView=search;
}
//2.設定tableView的資料
//設定有多少行資料
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// return 10;
return self.persons.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//1.去緩衝中取cll,若沒有則自己建立並標記
static NSString *ID=@"ID";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
//2.設定每個cell的資料
//先取出資料模型
YYPerson *person=self.persons[indexPath.row];
//設定這個cell的姓名(name)和年齡
cell.textLabel.text=person.name;
cell.detailTextLabel.text=[NSString stringWithFormat:@"年齡 %d",person.age];
//3.返回cell
return cell;
}
- (IBAction)add:(UIBarButtonItem *)sender {
// 初始化一些假資料
NSArray *names = @[@"西門抽血", @"西門抽筋", @"西門抽風", @"西門吹雪", @"東門抽血", @"東門抽筋", @"東門抽風", @"東門吹雪", @"北門抽血", @"北門抽筋", @"南門抽風", @"南門吹雪"];
for (int i = 0; i<20; i++) {
YYPerson *p = [[YYPerson alloc] init];
p.name = [NSString stringWithFormat:@"%@-%d", names[arc4random_uniform(names.count)], arc4random_uniform(100)];
p.age = arc4random_uniform(20) + 20;
[YYPersonTool save:p];
}
}
#pragma mark-搜尋方塊的代理方法
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
self.persons=[YYPersonTool queryWithCondition:searchText];
//重新整理表格
[self.tableView reloadData];
[searchBar resignFirstResponder];
}
@end
實現效果:
二、簡單說明
關於: NSString *NSsql=[NSString stringWithFormat:@"SELECT id,name,age FROM t_person WHERE name like '%%%@%%' ORDER BY age ASC;",condition];
注意:name like ‘西門',相當於是name = ‘西門'。
name like ‘%西%',為模二、簡單說明
關於: NSString *NSsql=[NSString stringWithFormat:@"SELECT id,name,age FROM t_person WHERE name like '%%%@%%' ORDER BY age ASC;",condition];
注意:name like ‘西門',相當於是name = ‘西門'。
name like ‘%西%',為模糊搜尋,搜尋字串中間包含了'西',左邊可以為任一字元串,右邊可以為任一字元串,的字串。
但是在 stringWithFormat:中%是逸出字元,兩個%才表示一個%。
列印查看:糊搜尋,搜尋字串中間包含了'西',左邊可以為任一字元串,右邊可以為任一字元串,的字串。
但是在 stringWithFormat:中%是逸出字元,兩個%才表示一個%。
SQLite常用的函數
一、簡單說明
1.開啟資料庫
複製代碼 代碼如下:
int sqlite3_open(
const char *filename, // 資料庫的檔案路徑
sqlite3 **ppDb // 資料庫執行個體
);
2.執行任何SQL語句
複製代碼 代碼如下:
int sqlite3_exec(
sqlite3*, // 一個開啟的資料庫執行個體
const char *sql, // 需要執行的SQL語句
int (*callback)(void*,int,char**,char**), // SQL語句執行完畢後的回調
void *, // 回呼函數的第1個參數
char **errmsg // 錯誤資訊
);
3.檢查SQL語句的合法性(查詢前的準備)
複製代碼 代碼如下:
int sqlite3_prepare_v2(
sqlite3 *db, // 資料庫執行個體
const char *zSql, // 需要檢查的SQL語句
int nByte, // SQL語句的最大位元組長度
sqlite3_stmt **ppStmt, // sqlite3_stmt執行個體,用來獲得資料庫資料
const char **pzTail
);
4.查詢一行資料
複製代碼 代碼如下:
int sqlite3_step(sqlite3_stmt*); // 如果查詢到一行資料,就會返回SQLITE_ROW
5.利用stmt獲得某一欄位的值(欄位的下標從0開始)
複製代碼 代碼如下:
double sqlite3_column_double(sqlite3_stmt*, int iCol); // 浮點數據
int sqlite3_column_int(sqlite3_stmt*, int iCol); // 整型資料
sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); // 長整型資料
const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); // 二進位文本資料
const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); // 字串資料
二、SQLite編碼
1.建立、開啟、關閉資料庫
建立或開啟資料庫
複製代碼 代碼如下:
// path是資料庫檔案的存放路徑
sqlite3 *db = NULL;
int result = sqlite3_open([path UTF8String], &db);
代碼解析:
sqlite3_open()將根據檔案路徑開啟資料庫,如果不存在,則會建立一個新的資料庫。如果result等於常量SQLITE_OK,則表示成功開啟資料庫
sqlite3 *db:一個開啟的資料庫執行個體
資料庫檔案的路徑必須以C字串(而非NSString)傳入
關閉資料庫:sqlite3_close(db);
2.執行不返回資料的SQL語句
執行創表語句
複製代碼 代碼如下:
char *errorMsg = NULL; // 用來儲存錯誤資訊
char *sql = "create table if not exists t_person(id integer primary key autoincrement, name text, age integer);";
int result = sqlite3_exec(db, sql, NULL, NULL, &errorMsg);
代碼解析:
sqlite3_exec()可以執行任何SQL語句,比如創表、更新、插入和刪除操作。但是一般不用它執行查詢語句,因為它不會返回查詢到的資料
sqlite3_exec()還可以執行的語句:
(1)開啟事務:begin transaction;
(2)復原事務:rollback;
(3)提交事務:commit;
3.帶預留位置插入資料
複製代碼 代碼如下:
char *sql = "insert into t_person(name, age) values(?, ?);";
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
sqlite3_bind_text(stmt, 1, "母雞", -1, NULL);
sqlite3_bind_int(stmt, 2, 27);
}
if (sqlite3_step(stmt) != SQLITE_DONE) {
NSLog(@"插入資料錯誤");
}
sqlite3_finalize(stmt);
代碼解析:
sqlite3_prepare_v2()傳回值等於SQLITE_OK,說明SQL語句已經準備成功,沒有文法問題
sqlite3_bind_text():大部分綁定函數都只有3個參數
(1)第1個參數是sqlite3_stmt *類型
(2)第2個參數指預留位置的位置,第一個預留位置的位置是1,不是0
(3)第3個參數指預留位置要綁定的值
(4)第4個參數指在第3個參數中所傳遞資料的長度,對於C字串,可以傳遞-1代替字串的長度
(5)第5個參數是一個可選的函數回調,一般用於在語句執行後完成記憶體清理工作
sqlite_step():執行SQL語句,返回SQLITE_DONE代表成功執行完畢
sqlite_finalize():銷毀sqlite3_stmt *對象
4.查詢資料
複製代碼 代碼如下:
char *sql = "select id,name,age from t_person;";
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
int _id = sqlite3_column_int(stmt, 0);
char *_name = (char *)sqlite3_column_text(stmt, 1);
NSString *name = [NSString stringWithUTF8String:_name];
int _age = sqlite3_column_int(stmt, 2);
NSLog(@"id=%i, name=%@, age=%i", _id, name, _age);
}
}
sqlite3_finalize(stmt);
代碼解析:sqlite3_step()返回SQLITE_ROW代表遍曆到一條新記錄
sqlite3_column_*()用於擷取每個欄位對應的值,第2個參數是欄位的索引,從0開始