kowala's home

kowala's home
這裡是我的學習筆記,陸續增加中。
http://kowala21.blogspot.com

2011-06-14

C++ & MySQL 中文問題II

繼上一篇到現在,還是沒有解決在 C++ 使用 UTF-8 連線 MySQL 的問題,現在確定 connector 105 是不支援 UTF-8 的,此外 connector 106 也是不支援的。請參考官網的問答。 
Re: How can I use unicode using connector/C++?

No explicit unicode support yet. 1.0.6 (September 2009) will introduce a sql::String abstraction class as a first step toward multi-byte character sets. However, the step towards ICU or similar is not on the roadmap for the next months. 

那現在只能使用 big5 來連線及儲存資料了,也就是

        MySQL(big5)<-Connector(big5)->API(big5)

這種方式來連線,剛剛看到大陸的朋友已經解決這個問題,他使用gb2312,節錄文章如下(用紅色表示),這應該可以修改使用,繁體中文在 MySQL 中也是叫做 big5 ,但這樣就不能簡繁並列了,唯一的遺憾。
註:下面的#include xxxx符號秀出不來,我用全形符號代替

用MySQL Connector C++访问MySql数据库,中文UTF-8乱码的解决
作者:淡月清风 日期:2010-07-11

// MySqlTest.cpp : 定义控制台应用程序的入口点。
//
 
#include <iostream>
using namespace std;
 
//MySQL Connector C++ 1.0.5,接口跟Oracle的OCCI长的很像(跟JDBC也像),Oracle-MySql官方网站可下载
//D:\Program Files\MySQL\MySQL Connector C++ 1.0.5\include
//D:\Program Files\MySQL\MySQL Connector C++ 1.0.5\lib\opt
 
#include <mysql_connection.h
#include <cppconn/statement.h
#include <cppconn/exception.h
using namespace sql;
using namespace sql::mysql;
 
#pragma comment(lib,"mysqlcppconn.lib")
 
int main(int argc, char* argv[])
{
    try
    {
        //数据库连接
        MySQL_Connection MySqlConn("localhost","root","006355");
       
        //选择数据库(模式)
        MySqlConn.setSchema("test");
 
        Statement *pStatement = MySqlConn.createStatement();
 
        //在Mysql数据库中,我设置的编码是GB2312,但是这里读出的仍是UTF-8编码的字符
        //所以需这句来解决乱码问题
 
        //执行无记录集返回的语句
        pStatement->execute("set names gb2312");
 
        //执行有记录集返回的语句
        //注意反引号 "`",呵呵
        ResultSet* pRs=pStatement->executeQuery("Select * from `Users`");
 
        while (pRs->next())
        {
            cout< getInt("id")<
           
 
            string sChineseText=pRs->getString(2);
            cout< <<":";
           
            //输出汉字的编码
            //D5 C5 C8 FD               张三  ANSI/OEM936:GBK/GB2312
            //E5 BC A0 E4 B8 89    张三  UTF8
            for (size_t i=0;i
            {
                printf("%02X ",(unsigned char)sChineseText[i]);
            }
            cout<
 
            cout< getString("password")< <
        }
       
        pRs->close();
        pStatement->close();
        MySqlConn.close();
    }
    catch (SQLException& ex)
    {
        cout<<"Error:"< <
    }
 
    return 0;
}

沒有留言:

張貼留言

請提供您的寶貴意見 ;-)