sqlite和objective-c中的编码问题 [英] Encoding problem in sqlite and objective-c
问题描述
我有一个文件,其内容如下:
I have a file with contents something like this:
INSERT INTO table VALUES (NULL,'° F','Degrees Fahrenheit');
INSERT INTO table VALUES (NULL,'° C','Degrees Celsius');
现在,要解析这个,我有这样的东西:
Now, to parse this, I have something like this:
NSString *sql = [NSString stringWithContentsOfFile:filename];
将此字符串打印到控制台看起来正确.然后,我要用它做一个实际的插入语句:
Printing this string to the console looks correct. Then, I want to make an actual insert statement out of it:
const char *sqlString = [query UTF8String];
const char *endOfString;
if (sqlite3_prepare_v2(db, sqlString + nextStatementStart, -1, &stmt, &endOfString) != SQLITE_OK) {
return NO;
}
这时,检查查询仍会返回正确的结果.也就是说, sqlite_sql(stmt)
返回 INSERT INTO表VALUES(NULL,'°F','Degrees Fahrenheit');
At this point, checking the query still returns the correct result. That is, sqlite_sql(stmt)
returns INSERT INTO table VALUES (NULL,'° F','Degrees Fahrenheit');
所以我用 sqlite3_step(stmt);
这时,查看数据库将显示以下内容:
At this point, viewing the database reveals this:
1 |¬∞F |表示华氏温度
我不在任何地方使用任何_16函数(例如 sqlite_open16
).
I'm not using any _16 functions anywhere (like sqlite_open16
).
编码问题在哪里?我该如何解决?
Where is the encoding issue? How do I fix this?
推荐答案
stringWithContentsOfFile:
从OSX 10.4开始不推荐使用(不确定iPhone),但是您想在此处使用 stringWithContentsOfFile:encoding:error
stringWithContentsOfFile:
is deprecated as of OSX 10.4 (not sure about iPhone), but you want to specify the encoding here using stringWithContentsOfFile:encoding:error
文件
包含:
CREATE TABLE myvalues (foo TEXT, bar TEXT, baz TEXT);
INSERT INTO myvalues VALUES (NULL,'° F','Degrees Fahrenheit');
test.m包含(未提供错误处理):
test.m contains (no error handling provided):
int main(int argc, char** argv)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSString* s = [NSString stringWithContentsOfFile:@"file"
encoding:NSUTF8StringEncoding
error:nil];
NSLog(@"s: %@", s);
sqlite3* handle;
sqlite3_open("file.db", &handle);
sqlite3_exec(handle, [s UTF8String], NULL, NULL, NULL);
sqlite3_close(handle);
[pool release];
}
然后转储:
% sqlite3 file.db
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .dump
BEGIN TRANSACTION;
CREATE TABLE myvalues (foo TEXT, bar TEXT, baz TEXT);
INSERT INTO "myvalues" VALUES(NULL,'° F','Degrees Fahrenheit');
COMMIT;
这篇关于sqlite和objective-c中的编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!