看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) Win7 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) VC++(Win32 API) 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) MySQL C API 問題(Question): 各位前輩大家好 小弟最近找到一個VC++使用MySQL C API讀取MySQL的範例 顯示英文數字時沒有問題 可是要顯示中文的結果都是亂碼 編碼格式也設定utf8了 請各位大哥大姊幫幫小弟除錯 執行結果:http://i.imgur.com/UA2vKvO.jpg 資料庫設定:http://i.imgur.com/c2vxNJz.jpg 資料表內容:http://i.imgur.com/u31gzWx.jpg 程式碼(Code):(請善用置底文網頁, 記得排版) #include <Windows.h> #include <mysql.h> #include <string> #include <iostream> using namespace std; int main() { char user[] = "root"; char pswd[] = ""; char host[] = "localhost"; char table[] = "mms_gs"; unsigned int port = 3306; MYSQL myCont; MYSQL_RES *result; MYSQL_ROW sql_row; int res; mysql_init(&myCont); if (mysql_real_connect(&myCont, host, user, pswd, table, port, NULL, 0)) { mysql_query(&myCont, "SET NAMES utf8"); //设置编码格式 res = mysql_query(&myCont, "select * from mms_reserved");//查询 if (!res) { result = mysql_store_result(&myCont); if (result) { while (sql_row = mysql_fetch_row(result))//获取具体的数据 { cout << "BOOKNAME:" << sql_row[1] << endl; cout << " SIZE:" << sql_row[2] << endl; } } } else { cout << "query sql failed!" << endl; } } else { cout << "connect failed!" << endl; } if (result != NULL) mysql_free_result(result); mysql_close(&myCont); system("pause"); return 0; } 補充說明(Supplement): 程式碼網址(codepad):http://codepad.org/WR138lCu 程式碼網址(codepile):https://www.codepile.net/pile/ny77n1yq -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.136.21.182 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1492418671.A.F29.html
johnpage: Big5 04/17 18:24
謝謝 改BIG5就可以了!
LPH66: 應該說問題是在最後一步你把資料 cout 出來時編碼不對 04/17 22:16
LPH66: 沒弄錯的話你到取資料為止都是對的, 但你取得的資料是 utf8 04/17 22:16
LPH66: 但 cout 到 console 時因為 console 是 big5 就炸了 04/17 22:16
謝謝! 我剛剛有上網查一下 有改用wcout及printf("%ls"); 可是顯示結果還是亂碼 想請問該用哪種輸出 才能輸出utf8 謝謝您! ※ 編輯: chingyue (122.116.59.114), 04/18/2017 15:15:06
MOONRAKER: 在Linux下跑,用utf8終端機開,就有utf8了 04/18 15:43
可是我是在Win7及Win10下跑... 還是謝謝您!
johnpage: 執行 chcp 65001命令 04/18 16:02
謝謝您! 我用你的方法有找到一篇文章 解決了我的問題 THX! ※ 編輯: chingyue (122.116.59.114), 04/18/2017 16:44:46