Ios 如何在SQLite表中插入值

Ios 如何在SQLite表中插入值,ios,sqlite,Ios,Sqlite,这是我用来向表中插入数据的代码 sqlite3 *database; NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"mobdb.sqlite"]; if(sqlite3_open([dbPath UTF8String],&database)==SQLITE_OK) { const char *

这是我用来向表中插入数据的代码

sqlite3 *database;

NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"mobdb.sqlite"];
        if(sqlite3_open([dbPath UTF8String],&database)==SQLITE_OK)
        {   
            const char *sqlstatement = "INSERT INTO mobDetails (nMonId, nScore) VALUES (?,?)";
            sqlite3_stmt *compiledstatement;

            if(sqlite3_prepare_v2(database,sqlstatement , -1, &compiledstatement, NULL)==SQLITE_OK)
            {
                NSString * str1 =@"1";
                NSString * str2 =@"12";

                sqlite3_bind_int(compiledstatement, 1, [str1 integerValue]);
                sqlite3_bind_int(compiledstatement, 2, [str2 integerValue]);

                if(sqlite3_step(compiledstatement)==SQLITE_DONE)
                {
                    NSLog(@"done");
                }
                else
                {
                    NSLog(@"ERROR");
                }
                sqlite3_reset(compiledstatement);
            }
            else
            {
                NSAssert1(0, @"Error . '%s'", sqlite3_errmsg(database));
            }
            sqlite3_close(database);
        }
它显示“完成”消息,但没有插入到表中的数据,任何人都可以帮助我


另外,如何在表中插入字符串?

问题在于应用程序包是只读的(你可能在谷歌搜索了5分钟后发现了这一点)。因此,您无法在应用程序包中插入数据库

- (void) saveData
{
     sqlite3_stmt    *statement;
     const char *dbpath = [databasePath UTF8String];

     if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
     {
           NSString *insertSQL = [NSString stringWithFormat: 
             @"INSERT INTO CONTACTS 
             (name, address, phone) VALUES (\"%@\", \"%@\", \"%@\")", 
             name.text, address.text, phone.text];
           const char *insert_stmt = [insertSQL UTF8String];
           sqlite3_prepare_v2(contactDB, insert_stmt, 
             -1, &statement, NULL);
            if (sqlite3_step(statement) == SQLITE_DONE)
            {
                 status.text = @"Contact added";
                 name.text = @"";
                 address.text = @"";
                 phone.text = @"";
            } else {
                  status.text = @"Failed to add contact";
            }
            sqlite3_finalize(statement);
            sqlite3_close(contactDB);
    }
}
使用SQLite API的一个错误是,您调用的是
sqlite3\u reset()
,而
sqlite3\u finalize()
应该被调用。(谢谢@trojanfoe。)


(哦,这与Xcode完全没有关系。)

试着将mobdb.sqlite放在documents文件夹中,然后插入。“如何使用Xcode在sqlite表中插入值”-无论如何。Xcode不是SQLite编辑器。他仍然需要使用
finalize
而不是
reset
@特洛伊木马程序。公平地说,我已经修改了我的答案。我尝试了finalize,即使它不是working@Rajesh同样,因为DB在应用程序包中。将其复制到可写位置并仔细阅读。。。