在ios中,持久化用好幾種 方法,前面已經介紹了 兩種 ,一個是簡單的寫入檔案,另一個是加入了序列化並寫入檔案中,現在介紹 ios 中嵌入式資料庫sqlite3的初級應用 當然在使用sqlite3之前 你需要將libsqlite3.dylib這個類庫加入到你的項目中
//////////////////////////////////////////////////////////////////////////////////////////
- (NSString *)dataFilePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; //首先得到應用程式沙箱中Document檔案夾的路徑
return [documentsDirectory stringByAppendingPathComponent:kFilename]//返回你指定檔案的路徑
//////////////////////////////////////
開啟資料庫
sqlite3 *database;
if (sqlite3_open([filePath UTF8String], &database)) {
sqlite3_close(database);
NSAssert(0,@"Failed to open database");
}
///////////////////
建立資料庫
char *errorMsg;
NSString *createSQL = @"CREATE TABLE IF NOT EXISTS FIELDS (ROW INTEGER PRIMARY KEY,FIELD_DATA TEXT);";
if (sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg)!=SQLITE_OK) {
sqlite3_close(database);
NSAssert1(0,@"Error creating table:%s",errorMsg);
}
/////////////////////////
查詢
NSString *query = @"SELECT ROW, FIELD_DATA FROM FIELDS ORDER BY ROW";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil)==SQLITE_OK) {
while (sqlite3_step(statement)==SQLITE_ROW) {
int row = sqlite3_column_int(statement, 0);
char *rowData = (char *)sqlite3_column_text(statement, 1);
//NSString *fieldName = [[NSString alloc] initWithFormat:@"field&d",row];
//NSString *fieldValue = [[NSString alloc] initWithUTF8String:rowData];
//UITextField *field = [self valueForKey:fieldName];
//field.text = fieldValue;
//[fieldName release];
//[fieldValue release];
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
////////////////////////////////////////////////////
插入 更新
sqlite3 *database;
if (sqlite3_open([[self dataFilePath] UTF8String], &database)) {
sqlite3_close(database);
NSAssert(0,@"Failed to open database");
}
for (int i=1; i<=4; i++) {
NSString *fieldName = [[NSString alloc] initWithFormat:@"field%d",i];
UITextField *field = [self valueForKey:fieldName];
[fieldName release];
char *errorMsg;
char *update = "INSERT OR REPLACE INTO FIELDS (ROW,FIELD_DATA) VALUES(?,?);"; //這裡插入的值可以用nsstring替換,但是最好的做法是使用綁定,如果遇到特殊字元 這是不二選擇
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(database, update, -1, &stmt, nil)==SQLITE_OK) {
sqlite3_bind_int(stmt, 1, i);
sqlite3_bind_text(stmt, 2, [[field text] UTF8String], -1, NULL);
}
if (sqlite3_step(stmt)!=SQLITE_DONE) {
NSAssert(0,@"Error updating table:%s",errorMsg);
}
sqlite3_finalize(stmt);
}
sqlite3_close(database);
這是最基礎的sqlite3在ios中的應用 方法的具體應用請查詢文檔