【问题标题】:Error during insert statement with SQLite3 in iOS在 iOS 中使用 SQLite3 插入语句时出错
【发布时间】:2013-04-14 17:25:15
【问题描述】:

我正在尝试在 iOS 应用程序的 SQLite 3 数据库中插入一些数据。但是我不断收到一个对我没用的错误。

这是我试图插入的代码:

 @try {
        NSString *dbPath = [self.GetDocumentDirectory stringByAppendingPathComponent:@"knhb.sqlite"];
        BOOL success = [fileMgr fileExistsAtPath:dbPath];
        if(!success)
        {
            NSLog(@"Cannot locate database file '%@'.", dbPath);
        }
        if((sqlite3_open_v2([dbPath UTF8String], &db, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK))
        {
            NSLog(@"An error has occured.");
        }


        NSString *sqlString = [NSString stringWithFormat:@"INSERT INTO Profile (name, password) VALUES ('%@','%@')", name, password];

        const char *sql = [sqlString UTF8String];

        sqlite3_stmt *sqlStatement;

        if(sqlite3_prepare_v2(db, sql, 1, &sqlStatement, NULL) != SQLITE_OK)
        {
            NSLog(@"%s SQLITE_ERROR '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(db), sqlite3_errcode(db));
        }

        sqlite3_step(sqlStatement);
        sqlite3_finalize(sqlStatement);

        int lastInsert = sqlite3_last_insert_rowid(db);
        NSLog(@"lastinsertid:%d", lastInsert);

        sqlite3_close(db);
    }
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }

我的数据库表 Profile 有三列 idProfile、名称和密码。但由于 idProfile 是一个 int 和主键,我不必包含它,因为它是自动递增的。

我不断收到的错误是:SQLITE_ERROR 'near "I": syntax error' (1)

我正在写入 Documents 文件夹。

非常感谢任何帮助。

大安

【问题讨论】:

  • 您不应使用stringWithFormat 创建 SQL 语句。正确使用sqlite3_bind_XXX 函数调用来绑定值。也许您的用户名或密码中的字符会混淆查询。正确绑定值将解决此类问题。
  • 我试过这个,但我仍然得到同样的错误。 ('near "I": syntax error') 我现在的代码: const char *sql = "INSERT INTO Profile (name, password) VALUES (?,?)"; sqlite3_stmt *sqlStatement; if(sqlite3_prepare_v2(db, sql, 1, &sqlStatement, NULL) != SQLITE_OK) { NSLog(@"%s SQLITE_ERROR '%s' (%1d)", FUNCTION, sqlite3_errmsg(db), sqlite3_errcode(db)); } sqlite3_bind_text(sqlStatement, 1, [name UTF8String], -1, SQLITE_TRANSIENT); sqlite3_bind_text(sqlStatement, 2, [密码 UTF8String], -2, SQLITE_TRANSIENT);

标签: ios objective-c sqlite insert


【解决方案1】:

我不太清楚为什么,但我通过更改以下代码行来修复它:

if(sqlite3_prepare_v2(db, sql, 1, &sqlStatement, NULL) != SQLITE_OK)

我把它变成了:

if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)

不确定 1 或 -1 是什么意思。也许有人可以详细说明?

干杯!

【讨论】:

  • 当然。我应该注意到这一点。请参阅sqlite3_prepare_v2 的文档。第三个参数是查询的字符串长度。您说该字符串只有 1 个字符长。 -1 表示长度将在运行时使用strlen 确定。
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 2017-04-10
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多