以下是一些SQLite3的基本操作,主要是写给自己温习,同时也希望能帮到像我一样的新手!
注意:要在工程中的Frameworks中导入相应的libsqlite3.dylib文件,也许在相应的目录下存在多个以libsqlite3开头的文件,务必选择libsqlite3.dylib,它始终指向最新版的SQLite3库的别名。
打开数据库:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"database.sqlite"];//database.sqlite为自己定义数据库名称
NSFileManager *fileManager = [NSFileManager defaultManager];
databasePath_ = path;
BOOL find = [fileManager fileExistsAtPath:path];
if (!find) {
NSString *rePath = getBundleFilePath(@"database", @"sqlite");
NSData *dataFile = [NSData dataWithContentsOfFile:rePath];
[dataFile writeToFile:databasePath_ atomically:YES];
}
NSLog(@"Database file have already existed.");
if(sqlite3_open([path UTF8String], &database_) != SQLITE_OK) {
sqlite3_close(database_);
NSLog(@"Error: open database file.");
}
创建数据库:
NSString *creatSQL = @"CREATE TABLE IF NOT EXISTS FIELDS (ROW INTEGER PRIMARY KEY, FIELD_DATA TEXT);";
if (sqlite3_exec(database, [creatSQL UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK) {
sqlite3_close(database);
NSLog@"Error creating table");
}
对表的操作,以查询为例
NSString *query = @"SELECT ROW, FIELD_DATA FROM FIELDS ";
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 *fieldValue = [[NSString alloc] initWithUTF8String:rowData];
[fieldValue release];
}
sqlite3_finalize(statement);
}