【问题标题】:why Table is not created in sqlite in ios为什么不在ios的sqlite中创建表
【发布时间】:2014-08-27 15:39:48
【问题描述】:

这是我在现有数据库中添加表的代码。我的代码到达sqlite3_prepare_v2 的成功回调并给出日志table created,但是当我使用终端打开我的sqlite 数据库时,我看到没有创建表。我的数据库表名是 fz1.sqlite 由 pragma 声明的:#define kDBName @"fz1.sqlite"

-(sqlite3 *)mydb:(NSString *)query{



static sqlite3 *database;
static sqlite3_stmt *enableForeignKey;



if (database == NULL) {
    sqlite3 *newDBconnection;


    // first get the path for the document directory of the application
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dbpath = [paths objectAtIndex:0];
    NSString *path = [dbpath stringByAppendingPathComponent:kDBName];


    if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
        NSLog(@"Database Successfully Opened :)");
        database = newDBconnection;

        if (sqlite3_prepare_v2(database,[query UTF8String], -1, &enableForeignKey, NULL) != SQLITE_OK) {
            NSLog(@"ERROR IN PRAGMA!");
        }
        else{

            sqlite3_exec(database, [query UTF8String], NULL, NULL, NULL);

            NSLog(@"faiz's table created");
        }

        sqlite3_finalize(enableForeignKey);

    } else {
        NSLog(@"Error in opening database :(");
        database = NULL;
    }
}

return database;
  }

【问题讨论】:

  • sqlite3 如果你问它会告诉你出了什么问题。开始这样做,您将更接近解决您的问题。
  • 打印出您打开数据库的位置。对于 SQLite 新手来说,您没有在您认为的位置打开文件的几率高于 50:50。

标签: ios objective-c database sqlite


【解决方案1】:

您的实现似乎没有错误。我认为您正在打开放置在 Application 捆绑包中的 db 文件,它将使用您执行的查询进行更新。

启动应用程序后,数据库文件将被复制到 device/simulator 的文档目录中。因此,如果您在 iOS 模拟器中运行应用程序,请检查文档目录文件夹中的 db。

打开看看有没有更新。

带有 db 文件 iOS 模拟器的 Document Dir 的文件夹结构示例

/用户/XYZ/库/应用程序支持/iPhone 模拟器/7.1/Applications/B5EC1893-B38F-4AB4-AE7C-48EF685EE35F/Documents/db.sqlite

【讨论】:

  • OP 正在打开文档目录中的数据库,而不是应用程序包。
【解决方案2】:

如果您在调用-(sqlite3 *)mydb:(NSString *)query 之前使用[NSString stringWithFormat:@"YourSqlStatement %@ %@",parameter1,parameter2]; 或类似的东西将参数放入查询中,您可能是在自己注入SQL。如果您正在这样做,请尝试使用sqlite_bind_text 加载您的参数,然后使用sqlite_step 执行。

如果这与您的实现无关,请尝试记录 sqlite_exec 的输出并查看您的错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    相关资源
    最近更新 更多