由于MySQL 8.0.18登录的加密方式导致Visual Studio 2019 C++连接MySQL 8.0.18 失败,所以要在MySQL数据库中执行下面的语句。
1.ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'tpassword';
2.建立新的C++项目,在解决方案右键菜单中选择[属性]
3.需要在两个位置增加MySQL的关联
4.然后再代码中加入必要的头文件引用及对应声明
#include <mysql.h>
#pragma comment(lib,"wsock32.lib")
#pragma comment(lib,"libmysql.lib")
int main()
{
std::cout << "Hello World!\n";
//Link Mysql
MYSQL* conn;
MYSQL_RES* res;
MYSQL_ROW row;
const char* server = "localhost";
const char* user = "root";
const char* password = "Password"; // got tot keep my data secret
const char* database = "Database";
conn = mysql_init(NULL);
// connect to database
if (!mysql_real_connect(conn, server, user, password, database, 3306, NULL, 0))
{
std::cout << stderr << "%s\n" << mysql_error(conn);
return -1;
}
// send SQL query
if (mysql_query(conn, "select * from tables"))
{
std::cout << stderr << "%s\n" << mysql_error(conn);
return -1;
}
res = mysql_use_result(conn);
// output table name
while ((row = mysql_fetch_row(res)) != NULL)
{
printf("%s %s %s %s\n", row[0], row[1], row[2], row[3]);
}
// close connection
mysql_free_result(res);
mysql_close(conn);
}