首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用MySQL从C++数据库获取字符串时编码错误

问使用MySQL从C++数据库获取字符串时编码错误
EN

Stack Overflow用户
提问于 2013-12-07 11:54:17
回答 1查看 477关注 0票数 0

我正在Visual 2012中用C++编写一个MFC应用程序。App连接到MySQL数据库,并将每一行显示到列表框中。单词为俄文,数据库编码为cp1251。我使用以下代码设置了相同的字符集:

代码语言:javascript
复制
if (!mysql_set_character_set(mysql, "cp1251")) {
    statusBox.SetWindowText((CString)"CP1251 is set for MYSQL.");
}

但这根本帮不上忙。我使用以下代码显示数据:

代码语言:javascript
复制
while ((row = mysql_fetch_row(result)) != NULL) {
    CString string = (CString)row[1];
    listBox.AddString(string);
}

这段代码也没有帮助:

代码语言:javascript
复制
mysql_query(mysql, "set names cp1251");

请帮帮忙。如何正确地显示西里尔字母?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-08 00:30:56

当跨越使用不同字符编码的系统边界时,您必须在它们之间进行转换。在这种情况下,MySQL数据库使用CP 1251,而Windows (和CString)使用UTF-16。转换可能如下所示:

代码语言:javascript
复制
#if !defined(_UNICODE)
    #error Unicode configuration required
#endif

CString CPtoUnicode( const char* CPString, UINT CodePage ) {
    CString retValue;
    // Retrieve required string length
    int len = MultiByteToWideChar( CodePage, 0,
                                   CPString, -1,
                                   NULL, 0 );
    if ( len == 0 ) {
        // Error -> return empty string
        return retValue;
    }

    // Allocate CString's internal buffer
    LPWSTR buffer = retValue.GetBuffer( len );
    // Do the conversion
    MultiByteToWideChar( CodePage, 0,
                         CPString, -1,
                         buffer, len );
    // Return control of the buffer back to the CString object
    retValue.ReleaseBuffer();
    return retValue;
}

这应用于以下方面:

代码语言:javascript
复制
while ( ( row = mysql_fetch_row( result ) ) != NULL ) {
    CString string = CPtoUnicode( row[1], 1251 );
    listBox.AddString( string );
}

或者,您可以使用CString的内置转换支持,这需要将线程的区域设置为源编码(CP 1251)并使用转换构造函数。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20441041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档