對于數據的處理,大家可能有不同種的處理的方法,比如常用的Plist
,NSUserDefaults
,CoreData
,SQLite
等等,都是我們移動開發中常用的手段,對于各自的使用場景就不贅述了,想必大家都知道什么情況下用什么都應該知道,這篇文章呢主要和大家分享一下SQLite的用法,在oc
中的原始用法以及FMDB
第三方的使用。
//首先建一個類來管理數據庫,可以寫成單例也
#import "DataManger1.h"
#import "Contact.h"
#import <sqlite3.h>
static sqlite3 *_db;
@implementation DataManger1
/**
* 創建數據庫和表
*/
+ (void)initialize{
//創建數據庫
//獲取到Library下Cache文件夾的路徑
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [path stringByAppendingPathComponent:@"contact.sqlite"];
NSLog(@"%@",filePath);
//打開數據庫
if (sqlite3_open(filePath.UTF8String, &_db) == SQLITE_OK) {
NSLog(@"數據庫打開成功");
}else{
NSLog(@"數據庫打開失敗");
}
//創建表
NSString *sql = @"create table if not exists t_contact(id integer primary key autoincrement,name text);";
char *err = nil;
sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &err);
if (err) {
NSLog(@"創建表失敗");
}else{
NSLog(@"創建表成功");
}
}
//判斷sql語句是否正確
+ (BOOL)execSql:(NSString *)sql
{
BOOL flag;
char *err;
sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &err);
if (err) {
flag = NO;
NSLog(@"%s",err);
}else{
flag = YES;
}
return flag;
}
//保存到數據庫
+ (void)saveDataWithContact:(Contact *)contact{
NSString *sql = [NSString stringWithFormat:@"insert into t_contact (name) values ('%@');",contact.name];
BOOL flag = [self execSql:sql];
if (flag) {
NSLog(@"插入數據成功");
}else{
NSLog(@"插入數據失敗");
}
}
//查詢所有的數據
+ (NSArray *)contact{
return [self contactSQL:@"select *from t_contact"];
}
//查詢
+ (NSArray *)contactSQL:(NSString *)sql
{
NSMutableArray *array = [NSMutableArray array];
sqlite3_stmt *stmt;//輔助數據結構類型
//解析sql語句,解析完成以后放在輔助結構里
if (sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL) == SQLITE_OK) {
//查詢數據
while (sqlite3_step(stmt) == SQLITE_ROW) {
NSString *name = [NSString stringWithUTF8String:sqlite3_column_text(stmt, 1)];
Contact *c = [Contact ContactWithName:name];
[array addObject:c];
}
}
return array;
}
//sqlite3_prepare_v2(
// sqlite3 *db, /* Database handle */
// const char *zSql, /* SQL statement, UTF-8 encoded */
// int nByte, /* Maximum length of zSql in bytes. */ -1默認自動計算sql長度
// sqlite3_stmt **ppStmt, /* OUT: Statement handle */
// const char **pzTail /* OUT: Pointer to unused portion of zSql */
//);
//sqlite3_column_text(sqlite3_stmt*, int iCol) 字段什么類型,使用什么
//這個過程從執行sqlite3_step()執行一個準備語句得到的結果集的當前行中返回一個列
//第一個參數為從sqlite3_prepare返回來的prepared statement對象的指針,第二參數指定這一行中的想要被返回的列的索引
這是主要的數據庫系統的代碼,供大家參考學習,主要效果圖如下
查詢數據庫所得到的結果展示
基于
FMDB
的代碼也會貼出來,代碼我已經上傳到gitHub上,歡迎大家下載,記得點star哦。(https://github.com/markdashi/SQLite )