用 C++ 連接 MySQL 資料庫 – 使用 MySQL C API

環境
windows 10 64bit
Visual Studio 2019
MySQL Server 8.0.25 – X64

1. 安裝 MySQL

預設會安裝在 C:\Program Files\MySQL\MySQL Server 8.0

記得先建立一個自己的資料庫

2. 用 sql 指令建立資料表

-- ----------------------------
-- Table structure for test01
-- ----------------------------
DROP TABLE IF EXISTS `test01`;
CREATE TABLE `test01`  (
  `id` int(11) NOT NULL,
  `int_test` int(11) NOT NULL,
  `char_test` char(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `varchar_test` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `text_test` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of test01
-- ----------------------------
INSERT INTO `test01` VALUES (1, 100, 'a', 'Harry Potter', 'The novels chronicle the lives of a young wizard, Harry Potter, whom are students at Hogwarts School of Witchcraft and Wizardry.');
INSERT INTO `test01` VALUES (2, 200, 'b', '哈利波特', '是一部兒童奇幻文學系列小說,描寫主角哈利波特在霍格華茲魔法學校7年學習生活中的冒險故事。');
INSERT INTO `test01` VALUES (3, 300, 'c', 'ハリー・ポッター', '1990年代のイギリスを舞台に、魔法使いの少年ハリー・ポッターの学校生活。');

SET FOREIGN_KEY_CHECKS = 1;

3. Visual Studio 2019

設定成 x64

把 MySQL 安裝資料夾裡的 libmysql.dll 拿出來跟執行檔放在一起

main.cpp

#include <iostream>
using namespace std;

#include <C:/Program Files/MySQL/MySQL Server 8.0/include/mysql.h>

#ifdef _WIN64
#pragma comment(lib,"C:\\Program Files\\MySQL\\MySQL Server 8.0\\lib\\libmysql.lib")
#else
#endif

int main()
{
	MYSQL* mysql = new MYSQL;
	if (mysql_init(mysql) == 0)
	{
		cout << mysql_error(mysql) << endl;
	}

	mysql_set_character_set(mysql, "utf8");

	char szIP[256] = "127.0.0.1";	//不需要加 port
	char szUser[256] = "user";
	char szPassword[256] = "password";
	char szDBName[256] = "testdb01";

	if (mysql_real_connect(mysql, szIP, szUser, szPassword, szDBName, 0, NULL, 0) == 0)
	{
		cout << mysql_error(mysql) << endl;
	}

	char szSql[256] = "select * from test01";
	if (mysql_query(mysql, szSql) != 0)
	{
		cout << mysql_error(mysql) << endl;
	}

	MYSQL_RES* res;
	res = mysql_store_result(mysql);
	if (res == 0)
	{
		cout << mysql_error(mysql) << endl;
	}

	MYSQL_ROW row;

	char szID[256] = "";
	char szIntTest[256] = "";
	char szChar[256] = "";
	char szVarChar[256] = "";
	char szText[1024] = "";

	wchar_t szUniChar[1024] = L"";
	wchar_t szUniVarChar[1024] = L"";
	wchar_t szUniText[2048] = L"";

	while (row = mysql_fetch_row(res))
	{
		strcpy_s(szID, row[0]);
		strcpy_s(szIntTest, row[1]);
		strcpy_s(szChar, row[2]);		//這個取出來會是 utf8 字串
		strcpy_s(szVarChar, row[3]);	//這個取出來會是 utf8 字串
		strcpy_s(szText, row[4]);		//這個取出來會是 utf8 字串

		cout << "szID = " << szID << endl;
		cout << "szIntTest = " << szIntTest << endl;
		cout << "szChar = " << szChar << endl;
		cout << "szVarChar = " << szVarChar << endl;//utf8 字串直接印會是亂碼

		//這些是我自己寫的函式庫,可以把 utf8 改成 unicode 並印出
		hkstr::UTF8ToUnicode(szUniChar, szChar);
		hkstr::UTF8ToUnicode(szUniVarChar, szVarChar);
		hkstr::UTF8ToUnicode(szUniText, szText);
		hkstr::PrintfUnicode(L"szUniChar = %s\n", szUniChar);
		hkstr::PrintfUnicode(L"szUniVarChar = %s\n", szUniVarChar);
		hkstr::PrintfUnicode(L"szUniText = %s\n", szUniText);

		cout << endl;
	}

	//clean
	row = 0;
	mysql_free_result(res);

	mysql_close(mysql);
	mysql_library_end();
	if (mysql != 0)
	{
		delete mysql;
		mysql = 0;
	}

	system("pause");
	return 0;
}

執行結果

注意:如果出現
Host ‘XXX.XXX.XXX.XXX’ is not allowed to connect to this MySQL server
通常是因為是從其他電腦用 root 登入
這時候要新增其他的使用者帳號
還要設定登入的IP或網域
然後用這個使用者帳號登入

建議是先用其他的 MySQL 連線軟體登入看看
再來寫程式

參考網址
https://www.796t.com/article.php?id=60107
https://lihan.cc/2013/10/336/
https://www.aiwalls.com/mysql/02/32268.html

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *