1.創(chuàng)建或者打開數據庫
static sqlite3 *_db;
+ (void)initialize
{
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
// 拼接文件名
NSString *filePath = [cachePath stringByAppendingPathComponent:@"contact.sqlite"];
// 打開數據庫
if (sqlite3_open(filePath.UTF8String, &_db) == SQLITE_OK) {
NSLog(@"打開成功");
}else{
NSLog(@"打開失敗");
}
// 創(chuàng)建表格
NSString *sql = @"create table if not exists t_contact (id integer primary key autoincrement,name text,phone text);";
char *error;
sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &error);
if (error) {
NSLog(@"創(chuàng)建表格失敗");
}else{
NSLog(@"創(chuàng)建表格成功");
}
}
2.增刪改 oc封裝方法
+ (BOOL)execWithSql:(NSString *)sql
{
BOOL flag;
char *error;
sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &error);
if (error) {
flag = NO;
NSLog(@"%s",error);
}else{
flag = YES;
}
return flag;
}
注意
sqlite3_exec()可以執(zhí)行任何SQL語句概漱,比如創(chuàng)表承边、更新、插入和刪除操作闺骚。但是一般不用它執(zhí)行查詢語句梳猪,因為它不會返回查詢到的數據
sqlite3_exec()還可以執(zhí)行的語句:
開啟事務:begin transaction;
回滾事務:rollback;
提交事務:commit;
帶占位符帶數據插入
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個參數是sqlite3_stmt *類型
第2個參數指占位符的位置春弥,第一個占位符的位置是1呛哟,不是0
第3個參數指占位符要綁定的值
第4個參數指在第3個參數中所傳遞數據的長度,對于C字符串匿沛,可以傳遞-1代替字符串的長度
第5個參數是一個可選的函數回調扫责,一般用于在語句執(zhí)行后完成內存清理工作
sqlite_step():執(zhí)行SQL語句,返回SQLITE_DONE代表成功執(zhí)行完畢
sqlite_finalize():銷毀sqlite3_stmt *對象
3.查找
+ (NSArray *)contactWithSql:(NSString *)sql
{
NSMutableArray *arrM = [NSMutableArray array];
// 準備查詢逃呼,生成句柄鳖孤,操作查詢數據結果
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL) == SQLITE_OK) {
// 執(zhí)行句柄
while (sqlite3_step(stmt) == SQLITE_ROW) {
NSString *name = [NSString stringWithUTF8String:sqlite3_column_text(stmt, 1)];
NSString *phone = [NSString stringWithUTF8String:sqlite3_column_text(stmt, 2)];
Contact *c = [Contact contactWithName:name phone:phone];
[arrM addObject:c];
}
}
return arrM;
}
代碼解析
sqlite3_step()返回SQLITE_ROW代表遍歷到一條新記錄
sqlite3_column_*()用于獲取每個字段對應的值,第2個參數是字段的索引蜘渣,從0開始
4.模糊查詢
// o select * from t_contact where name like '%searchText%' or phone like '%searchText%'
// % 在stringWithFormat中有特殊意思
// %% == %
// 輸入一個文字淌铐,進行模糊查詢,查看下名字或者電話是否包含文字
NSString *sql = [NSString stringWithFormat:@"select * from t_contact where name like '%%%@%%' or phone like '%%%@%%';",searchText,searchText];