无法插入"字符到Sqlite DB [Objective-C]

时间:2015-06-09 07:39:05

标签: objective-c sqlite

我在sqlite数据库上插入一些数据,它运行正常,但我注意到我不能插入包含字符"的单词,这是一个常见的问题吗?我应该更改解析文本并编辑我找到的每个"字符吗?

这是我用来将数据插入我的数据库的代码:

UICollectionViewCell *cell = (UICollectionViewCell *)button.superview.superview;
        NSIndexPath *indexPath = [self.customCollectionView indexPathForCell:cell];
        FolderProducts *item = _feedItems[indexPath.item];

        sqlite3_stmt    *statement;
        const char *dbpath = [databasePath UTF8String];

        if (sqlite3_open(dbpath, &Carrello) == SQLITE_OK)
        {
            NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO CarrelloMese (titolo, codice, prezzo, urlImg) VALUES (\"%@\", \"%@\", \"%@\", \"%@\")",item.nomeProdotto, item.codice, item.prezzo, item.urlImg];

            const char *insert_stmt = [insertSQL UTF8String];

            sqlite3_prepare_v2(Carrello, insert_stmt, -1, &statement, NULL);

            if (sqlite3_step(statement) == SQLITE_DONE)
            {

            } else {

            }

            sqlite3_finalize(statement);
            sqlite3_close(Carrello);
        }

1 个答案:

答案 0 :(得分:2)

您需要使用sqlite3_bind_xxx()函数 绑定 您的SQLite语句。基本上,您从语句中删除所有变量(在您的情况下为%@)并将其替换为'?'。然后SQLite知道哪里有?是一个变量,因此不会与命令混淆。

例如,假设您想绑定单词" INSERT"。用? SQLite不会将其读作命令,然后标记错误。

阅读文档(上面的链接),了解有关如何使用绑定功能的完整信息。

以下是您的代码与绑定(UNTESTED)的相似之处:

sqlite3_stmt    *statement;
        const char *dbpath = [databasePath UTF8String];

        if (sqlite3_open(dbpath, &Carrello) == SQLITE_OK)
        {
            NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO CarrelloMese (titolo, codice, prezzo, urlImg) VALUES (?,?,?,?)"];

            const char *insert_stmt = [insertSQL UTF8String];

            sqlite3_prepare_v2(Carrello, insert_stmt, -1, &statement, NULL);

            if (sqlite3_bind_text(statement, 0, item.nomeProdotto.UTF8String, item.nomeProdotto.length, SQLITE_STATIC) != SQLITE_OK) {
                NSLog(@"An error occurred");
            }
            // Etc etc
            // SQLite bind works like this: sqlite_bind_text/int/e.t.c(sqlite3_stmt,index_of_variable, value); 
            // there are optionally parameters for text length and copy type SQLITE_STATIC and SQLITE_TRANSIENT.

            if (sqlite3_step(statement) == SQLITE_DONE)
            {

            } else {

            }

            sqlite3_finalize(statement);
            sqlite3_close(Carrello);
        }