Created
August 20, 2012 09:59
-
-
Save bricklife/3402767 to your computer and use it in GitHub Desktop.
MFC + Windows 版 MySQL で UTF-8 な日本語を扱う
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <my_global.h> | |
#include <mysql.h> | |
void TestMySQL() | |
{ | |
TRACE("MySQL client version: %s\n", mysql_get_client_info()); | |
MYSQL *conn = mysql_init(NULL); | |
if (conn == NULL) { | |
TRACE("Error %u: %s\n", mysql_errno(conn), mysql_error(conn)); | |
} | |
if (mysql_real_connect(conn, "127.0.0.1", "user", "pass", "testdb", 0, NULL, 0) == NULL) { | |
TRACE("Error %u: %s\n", mysql_errno(conn), mysql_error(conn)); | |
} | |
mysql_query(conn, "set names utf8"); | |
// SELECT | |
mysql_query(conn, "SELECT * FROM nihongo"); | |
MYSQL_RES *result = mysql_store_result(conn); | |
int num_fields = mysql_num_fields(result); | |
CString str = _T(""); | |
wchar_t bufUnicode[MAX_PATH]; | |
char bufUTF8[MAX_PATH]; | |
MYSQL_ROW row; | |
while ((row = mysql_fetch_row(result))) { | |
for (int i = 0; i < num_fields; i++) { | |
if (row[i] == NULL) { | |
TRACE("NULL "); | |
continue; | |
} | |
int iLenUnicode = MultiByteToWideChar(CP_UTF8, 0, row[i], -1, NULL, 0); | |
if (iLenUnicode <= sizeof(bufUnicode)/sizeof(bufUnicode[0])) { | |
MultiByteToWideChar(CP_UTF8, 0, row[i], -1, bufUnicode, MAX_PATH); | |
str += bufUnicode; | |
str += _T(", "); | |
} | |
} | |
TRACE("\n"); | |
} | |
mysql_free_result(result); | |
// INSERT | |
CTime now = CTime::GetCurrentTime(); | |
CString s_now = now.Format(_T("%Y-%m-%d %H:%M:%S")); | |
CString insert = _T("INSERT INTO nihongo VALUES('本日は") + s_now + _T("です')"); | |
wchar_t *p = insert.GetBuffer(); | |
int iLenUtf8 = WideCharToMultiByte(CP_UTF8, 0, p, -1, NULL, 0, NULL, NULL); | |
if (iLenUtf8 <= sizeof(bufUTF8)) { | |
WideCharToMultiByte(CP_UTF8, 0, p, -1, bufUTF8, sizeof(bufUTF8), NULL, NULL); | |
mysql_query(conn, bufUTF8); | |
} | |
insert.ReleaseBuffer(); | |
mysql_close(conn); | |
AfxMessageBox(str); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment