[英]how to import my.sqlite3 into my iPhone project in Xcode
我将locationsWOW.sqlite3文件拖到我的项目中并尝试加载它。控制台未显示有关NSLog(@"failed to open database!")
信息NSLog(@"failed to open database!")
; 但显示NSLog(@"database open");
而且,即使我将locationsWOW
的名称更改为不存在的位置(@"locations" ofType:@"sqlite3"];)
,该项目仍成功编译并且我的.sqlite数据库无法正常工作。任何人都可以帮助我一个初学者。
这是我的代码。
-(id)init{
if (self = [super init]) {
NSString *sqlite3DB = [[NSBundle mainBundle]pathForResource:@"locationsWOW" ofType:@"sqlite3"];
if (sqlite3_open([sqlite3DB UTF8String], &_database) != SQLITE_OK) {
NSLog(@"failed to open database!");
}
}
NSLog(@"database open");
return self;
}
首先,只需在代码中执行以下步骤
+(NSString *)databasePath
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *sql_Path=[paths objectAtIndex:0];
NSString *dbPath=[sql_Path stringByAppendingPathComponent:@"locationsWOW.sqlite"];
NSFileManager *fileMgr=[NSFileManager defaultManager];
BOOL success;
NSError *error;
success=[fileMgr fileExistsAtPath:dbPath];
if (!success) {
NSString *path=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"locationsWOW.sqlite"];
success=[fileMgr copyItemAtPath:path toPath:dbPath error:&error];
}
return dbPath;
}
创建表后
+(void)createTable
{
char *error;
NSString *filePath =[self databasePath];
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
NSString *strQuery=[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS TableName(id TEXT,name TEXT);"];
sqlite3_exec(database, [strQuery UTF8String], NULL, NULL, &error);
}
else
{
NSAssert(0, @"Table failed to create");
NSLog(@"TableName Table Not Created");
}
sqlite3_close(database);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.