【问题标题】:Encoding problem in sqlite and objective-csqlite和objective-c中的编码问题
【发布时间】:2009-11-04 01:49:42
【问题描述】:

我有一个文件,内容如下:

INSERT INTO table VALUES (NULL,'° F','Degrees Fahrenheit');
INSERT INTO table VALUES (NULL,'° C','Degrees Celsius');

现在,为了解析这个,我有这样的东西:

NSString *sql = [NSString stringWithContentsOfFile:filename];

将此字符串打印到控制台看起来是正确的。然后,我想用它做一个实际的插入语句:

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 table VALUES (NULL,'° F','Degrees Fahrenheit');

然后我用sqlite3_step(stmt); 运行它

此时,查看数据库会发现:

1|° F|Degrees Fahrenheit

我没有在任何地方使用任何 _16 函数(例如 sqlite_open16)。

编码问题在哪里?我该如何解决这个问题?

【问题讨论】:

    标签: objective-c iphone cocoa sqlite


    【解决方案1】:

    stringWithContentsOfFile: 自 OSX 10.4 起已弃用(不确定 iPhone),但您想在此处使用 stringWithContentsOfFile:encoding:error 指定编码

    file 包含:

    CREATE TABLE myvalues (foo TEXT, bar TEXT, baz TEXT);
    INSERT INTO myvalues VALUES (NULL,'° F','Degrees Fahrenheit');
    

    test.m 包含(未提供错误处理):

    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;
    

    【讨论】:

    • 谢谢。你知道为什么它会使用第二种方法而不是第一种方法,即使两个字符串在调试控制台中打印出完全相同的结果?
    • 我相信第一个将其编码为 ASCII 字符串,因此它被读入为两个字符:0xC2(否定)0xB0(无穷大)。然后当你发出 UTF8String 时,这两个 UTF 字符就出来了。但是,如果您将其作为 UTF8 编码字符串读入,则将其读入 1 个字符:0xC2B0(度数符号)。在此处搜索学位:www1.tip.nl/~t876506/utf8tbl.html
    • 严格的 ASCII 只有 0x00..0x7F(虽然我上次尝试 NSASCIIStringEncoding 时,Cocoa 的行为与 NSISOLatin1StringEncoding、IIRC 相同——但从不依赖它)。它看起来像是把它读作 MacRoman。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    相关资源
    最近更新 更多