1

自 2 周以来一直在尝试解决这个 xcode 问题,但在网上没有找到任何解决方案......

所以,我开发了一个 iphone 应用程序,它带有从 sqlite 数据库生成的 tableview(这部分没问题)。我有一个按钮,它在我的 tableview 中插入一个新行(这部分没问题),但我无法在 sqlite 数据库中插入数据。

我的功能是(我从一些教程中做到了):

- (void) insertMyObjectDataIntoDatabase: (MyObject*)myObj {
NSLog(@"Start Insertion");
//init DB
NSString *databaseName = @"bd_MyObjects.sqlite";
NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir =  [documentsPaths lastObject];//[documentsPaths objectAtIndex:0];
NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName]; //NSLog(@"databasePath = %@.", databasePath);
BOOL success;
NSFileManager *FileManager = [NSFileManager defaultManager];
NSError *error;
success = [FileManager fileExistsAtPath:databasePath];
if (!success) {
    NSLog(@"ERROR dans l'existence du fichier DB.");
} else {
    //NSString *databasePathFromApp = [[NSBundle mainBundle] pathForResource:@"bd_MyObjects" ofType:@"sqlite"];
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath ] stringByAppendingPathComponent:databaseName ];
    NSLog(@"databasePathFromApp = '%@'.", databasePathFromApp);
    //success = [FileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:&error];
    success = [FileManager fileExistsAtPath:databasePath];
    if (!success) {
        NSLog(@"ERROR - Failed to create writable database file with message - ErrorMsg='%@'.", [error localizedDescription]);
        NSLog(@"ERROR - copyItemAtPath: \n%@\n toPath:\n%@", databasePathFromApp, databasePath);
    } else {
        NSLog(@"OK - Database created - ErrorMsg='%@'.", [error localizedDescription]);

        //[FileManager release];
        //to setup database object
        sqlite3 *database;
        //int statusSqlOpening = sqlite3_open([databasePath UTF8String], &database);
        int statusSqlOpening = sqlite3_open_v2([databasePath UTF8String], &database, SQLITE_OPEN_READWRITE, nil);
        NSLog(@"statusSqlOpening='%d' - '%s'.", statusSqlOpening, sqlite3_errmsg(database));
        if (statusSqlOpening != SQLITE_OK) {
            NSLog(@"ERROR opening the database: statusSqlOpening='%d' - ErrorMsg='%s'.", statusSqlOpening, sqlite3_errmsg(database));
        } else {
            NSLog(@"OK - database opened: statusSqlOpening='%d' - ErrorMsg='%s'.", statusSqlOpening, sqlite3_errmsg(database));
            static sqlite3_stmt *compiledStatement;
            NSString *statement = [[NSString alloc] initWithFormat:@"INSERT INTO tb_MyObjects (DateOfMyObject, Quantity1, Quantity2) VALUES ('%@', %d, %d)", myObj.DateOfMyObject, myObj.Quantity1, myObj.Quantity2,];
            const char *sqlstatement = [statement UTF8String];
            NSLog(@"reqString = %s",sqlstatement);
            int statusSqlExecution = sqlite3_prepare_v2(database, sqlstatement, -1, &compiledStatement, NULL);
            //int statusSqlExecution = sqlite3_exec(database, sqlstatement, NULL, NULL, NULL);
            if (statusSqlExecution != SQLITE_OK) {
                //NSLog(@"Error when executing the request: statusSqlOpening='%d' - statusSqlExecution='%d' - statusSqlStep='%d' - ErrorMsg='%s'.", statusSqlOpening, statusSqlExecution, statusSqlStep, sqlite3_errmsg(database));
                NSLog(@"ERROR when executing the request: statusSqlOpening='%d' - statusSqlExecution='%d' - ErrorMsg='%s'.", statusSqlOpening, statusSqlExecution, sqlite3_errmsg(database));
            } else {
                NSLog(@"OK - request executed: statusSqlOpening='%d' - statusSqlExecution='%d' - ErrorMsg='%s'.", statusSqlOpening, statusSqlExecution, sqlite3_errmsg(database));
                //sqlite3_step(compliedstatement) executes the statement...
                int statusSqlStep = sqlite3_step(compiledStatement);
                if (statusSqlStep != SQLITE_DONE) {
                    NSLog(@"ERROR by inserting: statusSqlStep='%d' - ErrorMsg='%s'", statusSqlStep, sqlite3_errmsg(database));
                } else {
                    NSLog(@"OK - Data successfully inserted: statusSqlStep='%d' - ErrorMsg='%s'.", statusSqlStep, sqlite3_errmsg(database));
                }
            }
            sqlite3_finalize(compiledStatement);
        }
        //Closing DB
        sqlite3_close(database);
    }
}
}

当我在 iphone 模拟器上运行这个应用程序并单击我的按钮时,我有这些日志:

2012-08-09 14:40:09.980 apps[4850:c07] Start Insertion
2012-08-09 14:40:09.981 myApps[4850:c07] databasePathFromApp = '/Users/adictic/Library/Application Support/iPhone Simulator/5.1/Applications/FE129301-39F9-4883-8714-125A6BF16FC3/myApps.app/bd_MyObjects.sqlite'.
2012-08-09 14:40:09.981 myApps[4950:c07] databasePath = '/Users/adictic/Library/Application Support/iPhone Simulator/5.1/Applications/FE129301-39F9-4883-8714-125A6BF16FC3/Documents/bd_MyObjects.sqlite'.
2012-08-09 14:40:09.981 myApps[4850:c07] OK - Database created - ErrorMsg='(null)'.
2012-08-09 14:40:09.982 myApps[4850:c07] statusSqlOpening='0' - 'not an error'.
2012-08-09 14:40:09.982 myApps[4850:c07] OK - database opened: statusSqlOpening='0' - ErrorMsg='not an error'.
2012-08-09 14:40:09.982 myApps[4850:c07] reqString = INSERT INTO tb_MyObjects (DateOfMyObject, Quantity1, Quantity2) VALUES ('2012-08-09 12:40:09 +0000', 150, 150)
2012-08-09 14:40:09.983 myApps[4850:c07] ERROR when executing the request: statusSqlOpening='0' - statusSqlExecution='1' - ErrorMsg='no such table: tb_MyObjects'.

所以,我从这些日志中了解到:

  • 我的数据库已正确创建
  • 我的数据库已正确打开
  • 我的请求正确写入(我在 sqlite 管理器中运行它并正确插入数据)
  • 但是请求没有执行,表好像不存在?!-

我尝试更改 sqlite 文件的权限(chmod 777 /Users/adictic/Library/Application Support/iPhone Simulator/5.1/Applications/FE129301-39F9-4883-8714-125A6BF16FC3/myApps.app/bd_MyObjects.sqlite)但它没有任何影响。

我在 Xcode 4.4 上开发。

提前感谢您的帮助。

4

3 回答 3

1

您无法插入存储在应用程序包中的数据库,因为捆绑包已签名并且您正在有效地更改它。

您需要:

1) 使用 sqlite 命令行工具创建一个空的数据库文件和架构,将其存储在应用程序包中,然后在首次使用时将其复制到文档文件夹中。

2)首次使用时在文档文件夹中以编程方式创建空数据库文件和模式(这将是我的首选方法)。

于 2012-08-09T13:40:51.433 回答
0

在方法中做类似的事情,可能是initDatabase之类的:(原因是木马的答案,我只是想添加一些代码片段)

NSString *databaseName = @"bd_MyObjects.sqlite";

// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;

// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];

// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];

// If the database already exists then return without doing anything
if(success) return;

// If not then proceed to copy the database from the application to the users filesystem

// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
于 2012-08-09T13:44:55.113 回答
0

您的错误消息告诉您,您打开的任何数据库都没有表 tb_MyObjects 。您已经注释掉了实际将数据库从您的包复制到目录的行。请注意,在不存在的数据库上调用 open 将创建一个新的空数据库(其中没有表 tb_MyObjects)。如果您已经这样做过一次,那么您就是在玩一个空表,因为您注释掉了复制新表的代码。

于 2012-08-09T13:52:24.507 回答