首先附上SQL語句學習地址,供大家學習參考!
第一步獲取沙箱目錄
//定義數(shù)據(jù)庫名字
#define DBFILE_NAME @"NotesList.sqlite3"
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, TRUE) lastObject];
self.plistFilePath = [documentDirectory stringByAppendingPathComponent:DBFILE_NAME];
第二步:初始化數(shù)據(jù)庫
const char *cpath = [self.plistFilePath UTF8String];
if (sqlite3_open(cpath, &db) != SQLITE_OK) {
NSLog(@"數(shù)據(jù)庫打開失敗割卖。");
} else {
NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS Note (cdate TEXT PRIMARY KEY, content TEXT);"];
const char *cSql = [sql UTF8String];
if (sqlite3_exec(db, cSql, NULL, NULL, NULL) != SQLITE_OK) {
NSLog(@"建表失敗。");
}
}
sqlite3_close(db);
接下來就可以查詢,插入,刪除等動作了
以查詢?yōu)槔唧w步驟如下:
1.使用sqlite3_open函數(shù)打開數(shù)據(jù)庫
2.使用sqlite3_prepare_v2函數(shù)預處理SQL語句//將SQL變成二進制,提高執(zhí)行速度
3.使用sqlite3_bind_text函數(shù)綁定參數(shù)
4.使用sqlite3_step函數(shù)執(zhí)行sql語句,遍歷結果集
5.使用sqlite3_column_text等函數(shù)提取字段數(shù)據(jù)
6.使用sqlite3_finalize和sqlite3_close函數(shù)釋放資源
代碼如下:
//按照主鍵查詢數(shù)據(jù)方法
- (Note *)findById:(Note *)model {
const char *cpath = [self.plistFilePath UTF8String];
if (sqlite3_open(cpath, &db) != SQLITE_OK) {
NSLog(@"數(shù)據(jù)庫打開失敗。");
} else {
NSString *sql = @"SELECT cdate,content FROM Note where cdate =?";
const char *cSql = [sql UTF8String];
//語句對象
sqlite3_stmt *statement;
//預處理過程
if (sqlite3_prepare_v2(db, cSql, -1, &statement, NULL) == SQLITE_OK) {
//準備參數(shù)
NSString *strDate = [self.dateFormatter stringFromDate:model.date];
const char *cDate = [strDate UTF8String];
//綁定參數(shù)開始
sqlite3_bind_text(statement, 1, cDate, -1, NULL);
//執(zhí)行查詢
if (sqlite3_step(statement) == SQLITE_ROW) {
char *bufDate = (char *) sqlite3_column_text(statement, 0);
NSString *strDate = [[NSString alloc] initWithUTF8String:bufDate];
NSDate *date = [self.dateFormatter dateFromString:strDate];
char *bufContent = (char *) sqlite3_column_text(statement, 1);
NSString *strContent = [[NSString alloc] initWithUTF8String:bufContent];
Note *note = [[Note alloc] initWithDate:date content:strContent];
sqlite3_finalize(statement);
sqlite3_close(db);
return note;
}
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
return nil;
}
-
插入sql
NSString *sql = @"INSERT OR REPLACE INTO note (cdate, content) VALUES (?,?)";
-
修改sql
NSString *sql = @"UPDATE note set content=? where cdate =?";
-
查詢所有sql
NSString *sql = @"SELECT cdate,content FROM Note";