【问题标题】:Wrong encoding when getting a string from MySQL database with C++使用 C++ 从 MySQL 数据库获取字符串时编码错误
【发布时间】:2013-12-07 11:54:17
【问题描述】:

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

if (!mysql_set_character_set(mysql, "cp1251")) {
    statusBox.SetWindowText((CString)"CP1251 is set for MYSQL.");
}

但这根本没有帮助。 我使用此代码显示数据:

while ((row = mysql_fetch_row(result)) != NULL) {
    CString string = (CString)row[1];
    listBox.AddString(string);
}

此代码也无济于事:

mysql_query(mysql, "set names cp1251");

请帮忙。我应该怎么做才能正确显示西里尔字母?

【问题讨论】:

  • CString 不知道它应该使用 CP1251 对字符串进行编码。它可能使用 Unicode(取决于您的项目设置)。要将 DB 编码 (CP1251) 转换为 Unicode (UTF-16),请调用 MultiByteToWideChar
  • 你能给我一个例子,我应该如何使用它吗?

标签: c++ mysql visual-studio-2012 encoding mfc


【解决方案1】:

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

#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;
}

这应该按如下方式使用:

while ( ( row = mysql_fetch_row( result ) ) != NULL ) {
    CString string = CPtoUnicode( row[1], 1251 );
    listBox.AddString( string );
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 2023-03-29
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多