iOS FMDB删除记录报错 Code:1, Type:SQLiteGlobal, Msg:unrecognized token: "7

147 阅读2分钟

使用FMDB删除记录时不成功,并且报错信息如下:

[VCode-WCDB]Code:1, Type:SQLiteGlobal, Msg:unrecognized token: "79e0958e"
DB Error: 1 "unrecognized token: "79e0958e""
DB Query: delete from Bran_IM_MESSAGE where uniqueId = 79e0958e-3583-4e57-876d-9e9271ec6036

在使用 SQLite 进行数据库操作时,遇到“unrecognized token”错误通常是由于 SQL 语句的语法不正确。在你的错误信息中,问题可能出在如何处理 uniqueId 字段的值。

问题分析

从错误信息来看,你尝试执行如下 SQL 语句:

NSString *sqlStr = [NSString stringWithFormat:@"delete from Bran_IM_MESSAGE where uniqueId = %@", uniqueId];

DELETE FROM Bran_IM_MESSAGE WHERE uniqueId = 79e0958e-3583-4e57-876d-9e9271ec6036;
  • 79e0958e-3583-4e57-876d-9e9271ec6036 是一个典型的 UUID,通常 UUID 是以字符串形式存储的。
  • SQL 语句中,字符串类型的值需要用引号括起来。如果不加引号,SQLite 会误将其解释为非法的标识符或表达式的一部分。

解决方案

你应该用单引号将 UUID 括起来,确保它被正确地解析为字符串。因此,正确的 SQL 语句应该是:

NSString *sqlStr = @"delete from Bran_IM_MESSAGE where uniqueId = ?;";
executeResult = [db executeUpdate:sqlStr, uniqueId];

DELETE FROM Bran_IM_MESSAGE WHERE uniqueId = '79e0958e-3583-4e57-876d-9e9271ec6036';

通过将 UUID 放在单引号内,确保它被解释为一个字符串,这样可以有效避免 "unrecognized token" 的错误。参数化查询不但可以简化语法,还能提高安全性,是处理 SQL 数据的最佳实践。