【问题标题】:How to insert value in SQLite table [duplicate]如何在 SQLite 表中插入值 [重复]
【发布时间】:2014-01-20 16:51:53
【问题描述】:

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

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

它显示“完成”消息,但没有插入表中的数据可以帮助我。

还有如何在表格中插入字符串?

【问题讨论】:

  • 尝试将 mobdb.sqlite 放在文档文件夹中,然后插入。
  • “如何使用 xcode 在 sqlite 表中插入值” - 绝不。 Xcode 不是 SQLite 编辑器。

标签: ios sqlite


【解决方案1】:

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

使用 SQLite API 的一个问题是您正在调用 sqlite3_reset() 而应该调用 sqlite3_finalize()。 (感谢@trojanfoe。)

(哦,这与 Xcode完全无关。)

【讨论】:

  • 他仍然需要使用finalize而不是reset
  • @trojanfoe 很公平,我已经修改了我的答案。
  • 我试过 finalize 甚至它不工作
  • @Rajesh 再次,因为数据库在应用程序包中。将其复制到可写位置并仔细阅读...
【解决方案2】:
- (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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    相关资源
    最近更新 更多