環境: redhat 9, MySQL 5.1.32
需求: 使用 MySQL C API 挿入資料時中文有問題, 因為 mysql設置資料儲存為UTF-8
解決: 將big5字串轉成utf-8字串, 然後再將utf-8字串存成16進制再挿入MySQL
#include <iconv.h>
#include <string.h>
#include <errno.h>
#define USR_NAME_LEN 64
char user[USR_NAME_LEN]; //從檔案讀來的Big5字串會存在user
char wuser[2*sizeof(user)+2];
const char fromcode[] = "big5";
const char tocode[] = "utf-8";
iconv_t cd;
size_t in_size = sizeof(user);
char *inptr = user;
char out[2*USR_NAME_LEN+1];
size_t out_size = sizeof(out);
char *outptr = out;
if ((iconv_t)(-1) == (cd = iconv_open(tocode, fromcode))) {
printf("(%s)Failed to iconv_open %s to %s.\n",strerror(errno), fromcode, tocode);
exit(EXIT_FAILURE);
}
if ((size_t)(-1) == iconv(cd, &inptr, &in_size, &outptr, &out_size)) {
printf("Fail to convert characters to new code set.(%s)\n", strerror(errno));
exit(EXIT_FAILURE);
iconv_close(cd);
}
那麼使用MySQL C API便可insert中文資料了!
char sqlcmd[512];
mysql_hex_string(wuser, out, strlen(out) );
DataBase<mysql> dataBase("127.0.0.1", "root", "yourpassword", "dbname");
memset(sqlcmd, 0, sizeof sqlcmd);
sprintf(sqlcmd, "INSERT INTO tablename(username) VALUES(0x%s)"
,wuser);
dataBase << sqlcmd ;
libiconv 只有三個functions
iconv_t iconv_open (const char* tocode, const char* fromcode):開啟 libiconv。
size_t iconv (iconv_t cd, const char* * inbuf, size_t * inbytesleft, char* * outbuf, size_t * outbytesleft):執行轉碼。
int iconv_close (iconv_t cd):做完轉碼後關閉 libiconv。
This entry was posted
on 2009年4月29日 星期三
at 上午11:12
and is filed under
程式設計,
Linux
. You can follow any responses to this entry through the
comments feed
.