IPhone MySQL数据库操作代码例子
2010-10-21 01:38:52 来源:WEB开发网//database operation
打开数据库
-(BOOL) opendatabase{
NSArray*paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [pathsobjectAtIndex:0];
NSString *path = [documentsDirectorystringByAppendingPathComponent:@"mydb.sql"];
NSFileManager*fileManager = [NSFileManagerdefaultManager];
BOOL find = [fileManagerfileExistsAtPath:path];
//找到数据库文件mydb.sql
if (find) {
NSLog(@"Database file have already existed.");
if(sqlite3_open([pathUTF8String], &database_) !=SQLITE_OK) {
sqlite3_close(database_);
NSLog(@"Error: open database file.");
return NO;
}
return YES;
}
if(sqlite3_open([path UTF8String], &database_) ==SQLITE_OK) {
//bFirstCreate_ = YES;
[selfcreateChannelsTable:database_];//在后面实现函数createChannelsTable
return YES;
}else {
sqlite3_close(database_);
NSLog(@"Error: open database file.");
return NO;
}
return NO;
}
创建表
- (BOOL) createChannelsTable:(sqlite3*)db{
char*sql = "CREATE TABLE reports (id integer primary key,stime text,stitle text,scal text,sruntime text)";
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(db, sql, -1, &statement,nil) !=SQLITE_OK) {
NSLog(@"Error: failed to prepare statement:create reports table");
return NO;
}
int success =sqlite3_step(statement);
sqlite3_finalize(statement);
if ( success !=SQLITE_DONE) {
NSLog(@"Error: failed to dehydrate:CREATE TABLE reports");
return NO;
}
NSLog(@"Create table 'reports' successed.");
return YES;
赞助商链接