简体   繁体   English

如何在Xcode中将my.sqlite3导入我的iPhone项目

[英]how to import my.sqlite3 into my iPhone project in Xcode

I drag locationsWOW.sqlite3 file into my project and trying to load it in.The console did't show info about NSLog(@"failed to open database!") ; 我将locationsWOW.sqlite3文件拖到我的项目中并尝试加载它。控制台未显示有关NSLog(@"failed to open database!")信息NSLog(@"failed to open database!") but show NSLog(@"database open"); 但显示NSLog(@"database open"); And even when I change the name of locationsWOW to be locations (@"locations" ofType:@"sqlite3"];) which is not existing ,still the project successfully compiled and my .sqlite database didn't work.Any could help me a beginner. 而且,即使我将locationsWOW的名称更改为不存在的位置(@"locations" ofType:@"sqlite3"];) ,该项目仍成功编译并且我的.sqlite数据库无法正常工作。任何人都可以帮助我一个初学者。

Here is my code. 这是我的代码。

-(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;
}

As a beginer just do the following steps in your code 首先,只需在代码中执行以下步骤

+(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;
  }

After when create the Table 创建表后

+(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM