Cod*_*Guy 8 sqlite iphone objective-c ios
我发现在我的iPhone应用程序中更新/插入我的表时遇到问题,因为我有一个TEXT列,当该文本包含'符号时,事情就搞砸了.处理这个问题的最佳方法是什么?
在使用带撇号的字符串之前,我应该检查一下吗?有没有一种快速添加格式的方法,可以在每个撇号前添加转义字符?
这个问题甚至有意义吗?大声笑.
vig*_*o24 12
sqlite要求'符号被两个人逃脱'.
从官方的sqlite FAQ看看这个:
(14) How do I use a string literal that contains an embedded single-quote (') character?
The SQL standard specifies that single-quotes in strings are escaped by putting two single quotes in a row. SQL works like the Pascal programming language in the regard. SQLite follows this standard. Example:
INSERT INTO xyz VALUES('5 O''clock');
有三种方法可以解决这个问题:
sqlite3_mprintf("%Q")有SQLite的做到这一点.(%q引用替换; %Q引用替换并为空指针插入NULL.)sqlite3_bind_text.这是执行此操作的最佳方法,因为它不需要为每个字符串重新编译语句,也不会打开SQL注入.使用绑定看起来像这样:
sqlite3_prepare(db, "INSERT INTO Table(Column) VALUES(?);", -1, &stmt, NULL);
sqlite3_bind_text(stmt, 1, [str cStringUsingEncoding:NSUTF8StringEncoding],
-1, SQLITE_TRANSIENT);
// stepping, etc
Run Code Online (Sandbox Code Playgroud)
(不要忘记进行错误检查.)
嘿忘了所有这些东西.如果你想让你的数据库包含'.只需用%27替换你的字符串,并在取回它时将其转换回来.你会得到你想要的.检查如下:
// while Inserting into db
str = [str stringByReplacingOccurrencesOfString:@"'" withString:@"%27"];
// while fetching it back
text = [text stringByReplacingOccurrencesOfString:@"%27" withString:@"'"];
Run Code Online (Sandbox Code Playgroud)
享受编程:) :)
| 归档时间: |
|
| 查看次数: |
5335 次 |
| 最近记录: |