-1

I tried to implement to insert data to sqlite database in many ways. In run time, the code executed returns the id that is inserted but when I check the database, nothing is inserted. Does anyone know what is the problem? Many thanks in advance. The code I implemented here:

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

    }
}
4

1 回答 1

5

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

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

编辑:

您还应该更改对sqlite3_opento的使用sqlite3_open_v2。这给了你更多的控制权。

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

于 2012-11-20T04:44:18.533 回答