插入语句在运行时执行,但数据未插入iPhone中的数据库中

时间:2012-11-20 04:32:54

标签: iphone objective-c cocoa-touch sqlite

我尝试实现以多种方式将数据插入sqlite数据库。在运行时,执行的代码返回插入的id,但是当我检查数据库时,没有插入任何内容。有谁知道这是什么问题?提前谢谢了。 我在这里实现的代码:

sqlite3 *database;
sqlite3_stmt *addStmt;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"MoviePlayerMgmt.rdb"];
BOOL success =[fileMgr fileExistsAtPath:dbPath];
if(!success)
{
    NSLog(@"Cannot locate file %@",dbPath);

}
else{
    NSLog(@"__________Open the file__________ %@",dbPath);

    if(!(sqlite3_open([dbPath UTF8String], &database)==SQLITE_OK))
    {
        NSLog(@"An error has occured: %@",[NSString stringWithUTF8String:(char *) sqlite3_errmsg(database)]);
    }
    else{
        NSLog(@"Open database");
        NSString *strName = txtName.text;
                              NSLog(@"Computer name is %@",strName);
                             NSString *strIP = txtIP.text;
                             NSString *strPort = txtPort.text;
        NSString *insertStatement = [NSString stringWithFormat:@"INSERT INTO COMPUTER (computerName, IPAddress, portNumber) VALUES (\"%@\", \"%@\", \"%@\")", strName, strIP, strPort];

        char *error;
        if ( sqlite3_exec(database, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
        {
            int computerID = sqlite3_last_insert_rowid(database);


              NSLog(@"A computer inserted. %d",computerID);
              sqlite3_close(database);
        }
        else
        {
            NSLog(@"Error: %s", error);
        }

    }
}

1 个答案:

答案 0 :(得分:5)

应用的资源包是只读的(至少在真实的iOS设备上)。您无法在应用程序的资源包中写入数据库。

第一次运行应用程序时,您需要将应用程序包中的初始数据库复制到应用程序沙箱中的另一个可写目录。然后你总是使用这个副本进行阅读和写作。

编辑:

您还应该将sqlite3_open的使用更改为sqlite3_open_v2。这样可以让您获得更多控制权。

另外,不要使用字符串格式创建类似insert语句的查询。你应该用?创建查询?每个变量的符号。然后使用适当的sqlite3_bind_xxx函数将正确的值绑定到语句。这将确保正确转义值。