我正在Visual 2012中用C++编写一个MFC应用程序。App连接到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");请帮帮忙。如何正确地显示西里尔字母?
发布于 2013-12-08 00:30:56
当跨越使用不同字符编码的系统边界时,您必须在它们之间进行转换。在这种情况下,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 );
}或者,您可以使用CString的内置转换支持,这需要将线程的区域设置为源编码(CP 1251)并使用转换构造函数。
https://stackoverflow.com/questions/20441041
复制相似问题