C++操作mysql數據庫范例代碼
C++操作mysql數據庫范例代碼
#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);}</pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!