SQLite模糊查詢
一、示例
說明:本文簡單示例了SQLite的模糊查詢
1.新建一個繼承自NSObject的模型
該類中的代碼:
#import <Foundation/Foundation.h>
@interface YYPerson : NSObject
@property (nonatomic, assign) int ID;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@end
工具類中的代碼設(shè)計如下:
YYPersonTool.h文件
#import <Foundation/Foundation.h>
@class YYPerson;
@interface YYPersonTool : NSObject
/**
* 保存一個聯(lián)系人
*/
+ (void)save:( YYPerson*)person;
/**
* 查詢所有的聯(lián)系人
*/
+ (NSArray *)query;
+ (NSArray *)queryWithCondition:(NSString *)condition;
@end
#import "YYPersonTool.h"
#import "YYPerson.h"
#import <sqlite3.h>
@interface YYPersonTool ()
//@property(nonatomic,assign)sqlite3 *db;
@end
static sqlite3 *_db;
//首先需要有數(shù)據(jù)庫
+(void)initialize
{
//獲得數(shù)據(jù)庫文件的路徑
NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName=[doc stringByAppendingPathComponent:@"person.sqlite"];
//將OC字符串轉(zhuǎn)換為c語言的字符串
const char *cfileName=fileName.UTF8String;
//1.打開數(shù)據(jù)庫文件(如果數(shù)據(jù)庫文件不存在,那么該函數(shù)會自動創(chuàng)建數(shù)據(jù)庫文件)
int result = sqlite3_open(cfileName, &_db);
if (result==SQLITE_OK) { //打開成功
NSLog(@"成功打開數(shù)據(jù)庫");
//2.創(chuàng)建表
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(@"創(chuàng)表成功");
}else
{
printf("創(chuàng)表失敗---%s",errmsg);
}
}else
{
NSLog(@"打開數(shù)據(jù)庫失敗");
}
}
//保存一條數(shù)據(jù)
+(void)save:(YYPerson *)person
{
//1.拼接SQL語句
NSString *sql=[NSString stringWithFormat:@"INSERT INTO t_person (name,age) VALUES ('%@',%d);",person.name,person.age];
//2.執(zhí)行SQL語句
char *errmsg=NULL;
sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &errmsg);
if (errmsg) {//如果有錯誤信息
NSLog(@"插入數(shù)據(jù)失敗--%s",errmsg);
}else
{
NSLog(@"插入數(shù)據(jù)成功");
}
}
+(NSArray *)query
{
return [self queryWithCondition:@""];
}
//模糊查詢
+(NSArray *)queryWithCondition:(NSString *)condition
{
//數(shù)組,用來存放所有查詢到的聯(lián)系人
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];
//每調(diào)用一次sqlite3_step函數(shù),stmt就會指向下一條記錄
while (sqlite3_step(stmt)==SQLITE_ROW) {//找到一條記錄
//取出數(shù)據(jù)
//(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
在代碼中,讓主控制器直接繼承自UITableViewController
代碼設(shè)計如下:
YYViewController.m文件
#import "YYViewController.h"
#import "YYPerson.h"
#import "YYPersonTool.h"
@interface YYViewController ()<UISearchBarDelegate>
//添加一個數(shù)組,用來保存person
@property(nonatomic,strong)NSArray *persons;
@end
#pragma mark-懶加載
-(NSArray *)persons
{
if (_persons==nil) {
_persons=[YYPersonTool query];
}
return _persons;
}
//1.在初始化方法中添加一個搜索框
- (void)viewDidLoad
{
[super viewDidLoad];
//設(shè)置搜索框
UISearchBar *search=[[UISearchBar alloc]init];
search.frame=CGRectMake(0, 0, 300, 44);
search.delegate=self;
self.navigationItem.titleView=search;
}
//2.設(shè)置tableView的數(shù)據(jù)
//設(shè)置有多少行數(shù)據(jù)
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// return 10;
return self.persons.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//1.去緩存中取cll,若沒有則自己創(chuàng)建并標記
static NSString *ID=@"ID";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
//2.設(shè)置每個cell的數(shù)據(jù)
//先取出數(shù)據(jù)模型
YYPerson *person=self.persons[indexPath.row];
//設(shè)置這個cell的姓名(name)和年齡
cell.textLabel.text=person.name;
cell.detailTextLabel.text=[NSString stringWithFormat:@"年齡 %d",person.age];
//3.返回cell
return cell;
}
- (IBAction)add:(UIBarButtonItem *)sender {
// 初始化一些假數(shù)據(jù)
NSArray *names = @[@"西門抽血", @"西門抽筋", @"西門抽風(fēng)", @"西門吹雪", @"東門抽血", @"東門抽筋", @"東門抽風(fēng)", @"東門吹雪", @"北門抽血", @"北門抽筋", @"南門抽風(fēng)", @"南門吹雪"];
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
二、簡單說明
關(guān)于: NSString *NSsql=[NSString stringWithFormat:@"SELECT id,name,age FROM t_person WHERE name like '%%%@%%' ORDER BY age ASC;",condition];
注意:name like ‘西門',相當于是name = ‘西門'。
name like ‘%西%',為模二、簡單說明
關(guān)于: 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:中%是轉(zhuǎn)義字符,兩個%才表示一個%。
打印查看:糊搜索,搜索字符串中間包含了'西',左邊可以為任意字符串,右邊可以為任意字符串,的字符串。
但是在 stringWithFormat:中%是轉(zhuǎn)義字符,兩個%才表示一個%。
SQLite常用的函數(shù)
一、簡單說明
1.打開數(shù)據(jù)庫
const char *filename, // 數(shù)據(jù)庫的文件路徑
sqlite3 **ppDb // 數(shù)據(jù)庫實例
);
2.執(zhí)行任何SQL語句
sqlite3*, // 一個打開的數(shù)據(jù)庫實例
const char *sql, // 需要執(zhí)行的SQL語句
int (*callback)(void*,int,char**,char**), // SQL語句執(zhí)行完畢后的回調(diào)
void *, // 回調(diào)函數(shù)的第1個參數(shù)
char **errmsg // 錯誤信息
);
3.檢查SQL語句的合法性(查詢前的準備)
sqlite3 *db, // 數(shù)據(jù)庫實例
const char *zSql, // 需要檢查的SQL語句
int nByte, // SQL語句的最大字節(jié)長度
sqlite3_stmt **ppStmt, // sqlite3_stmt實例,用來獲得數(shù)據(jù)庫數(shù)據(jù)
const char **pzTail
);
4.查詢一行數(shù)據(jù)
int sqlite3_column_int(sqlite3_stmt*, int iCol); // 整型數(shù)據(jù)
sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); // 長整型數(shù)據(jù)
const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); // 二進制文本數(shù)據(jù)
const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); // 字符串數(shù)據(jù)
二、SQLite編碼
1.創(chuàng)建、打開、關(guān)閉數(shù)據(jù)庫
創(chuàng)建或打開數(shù)據(jù)庫
sqlite3 *db = NULL;
int result = sqlite3_open([path UTF8String], &db);
代碼解析:
sqlite3_open()將根據(jù)文件路徑打開數(shù)據(jù)庫,如果不存在,則會創(chuàng)建一個新的數(shù)據(jù)庫。如果result等于常量SQLITE_OK,則表示成功打開數(shù)據(jù)庫
sqlite3 *db:一個打開的數(shù)據(jù)庫實例
數(shù)據(jù)庫文件的路徑必須以C字符串(而非NSString)傳入
關(guān)閉數(shù)據(jù)庫:sqlite3_close(db);
2.執(zhí)行不返回數(shù)據(jù)的SQL語句
執(zhí)行創(chuàng)表語句
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()可以執(zhí)行任何SQL語句,比如創(chuàng)表、更新、插入和刪除操作。但是一般不用它執(zhí)行查詢語句,因為它不會返回查詢到的數(shù)據(jù)
sqlite3_exec()還可以執(zhí)行的語句:
(1)開啟事務(wù):begin transaction;
(2)回滾事務(wù):rollback;
(3)提交事務(wù):commit;
3.帶占位符插入數(shù)據(jù)
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(@"插入數(shù)據(jù)錯誤");
}
sqlite3_finalize(stmt);
代碼解析:
sqlite3_prepare_v2()返回值等于SQLITE_OK,說明SQL語句已經(jīng)準備成功,沒有語法問題
sqlite3_bind_text():大部分綁定函數(shù)都只有3個參數(shù)
(1)第1個參數(shù)是sqlite3_stmt *類型
(2)第2個參數(shù)指占位符的位置,第一個占位符的位置是1,不是0
(3)第3個參數(shù)指占位符要綁定的值
(4)第4個參數(shù)指在第3個參數(shù)中所傳遞數(shù)據(jù)的長度,對于C字符串,可以傳遞-1代替字符串的長度
(5)第5個參數(shù)是一個可選的函數(shù)回調(diào),一般用于在語句執(zhí)行后完成內(nèi)存清理工作
sqlite_step():執(zhí)行SQL語句,返回SQLITE_DONE代表成功執(zhí)行完畢
sqlite_finalize():銷毀sqlite3_stmt *對象
4.查詢數(shù)據(jù)
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_*()用于獲取每個字段對應(yīng)的值,第2個參數(shù)是字段的索引,從0開始
新聞熱點
疑難解答