使用SQLite数据库存储数据(1)-操作SQLite数据库
在使用SQLite API函數(shù)如有疑問,可以參考官方函數(shù)文檔:
http://www.sqlite.org/c3ref/funclist.html
操作SQLite數(shù)據(jù)庫
SQLite數(shù)據(jù)庫是文件數(shù)據(jù)庫,是保存在文件系統(tǒng)中的。因此需要知道文件保存到哪里,下面的代碼中,我們將Notebook.sqlite數(shù)據(jù)庫存放在Documents目錄下。其中涉及到SQLite數(shù)據(jù)庫的創(chuàng)建、打開、創(chuàng)建數(shù)據(jù)表和關(guān)閉數(shù)據(jù)庫等等操作。
NSString *docsDir;
NSArray *dirPaths;
// 獲取 documents 目錄
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// 構(gòu)造數(shù)據(jù)庫文件路徑
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"Notebook.sqlite"]];
NSFileManager *fileMgr = [NSFileManager defaultManager];
if([fileMgr fileExistsAtPath:databasePath] == NO){
const char *dbpath = [databasePath UTF8String];
// 創(chuàng)建數(shù)據(jù)庫,并打開數(shù)據(jù)庫
// SQLite的策略是如果有該文件就打開,如果沒有就創(chuàng)建文件,也就是創(chuàng)建數(shù)據(jù)庫。
if (sqlite3_open(dbpath, ¬eDB) == SQLITE_OK) {
char *errMsg;
const char *sql_str ="CREATE TABLE IF NOT EXISTS Notebook (ID INTEGER? PRIMARY KEY AUTOINCREMENT, Whattime Text, Address TEXT, What TEXT, Who TEXT, NOTE TEXT)";
// 創(chuàng)建數(shù)據(jù)表 Notebook
if(sqlite3_exec(noteDB, sql_str, NULL, NULL, &errMsg) != SQLITE_OK){
NSLog(@"Failed to create table");
}
?
?
// 關(guān)閉數(shù)據(jù)庫
sqlite3_close(noteDB);
} else {
NSLog(@"Failed to open/create database");
}
}
SQLite的策略是如果有該數(shù)據(jù)庫文件就打開,如果沒有就創(chuàng)建文件,也就是創(chuàng)建數(shù)據(jù)庫。這里要注意,使用的是C語法,sqlite3_open傳入的是數(shù)據(jù)庫的地址。
下面的代碼負(fù)責(zé)將NSString 對象轉(zhuǎn)換為const char * 的C類型數(shù)據(jù)。
const char *dbpath = [databasePath UTF8String];
在調(diào)用sqlite3_exec(noteDB, sql_str, NULL, NULL, &errMsg)函數(shù)時,errMsg傳的是地址,因為該函數(shù)要通過地址引用來寫報錯字符信息。
轉(zhuǎn)載于:https://www.cnblogs.com/tuncaysanli/archive/2012/10/17/2727947.html
總結(jié)
以上是生活随笔為你收集整理的使用SQLite数据库存储数据(1)-操作SQLite数据库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (转)PCB中各层的含义(protel中
- 下一篇: 35个非主流开源数据库