1.linux使用Ubuntu
2.Ubuntu安装vscode
2.1 安装的是snap版本,直接打开命令行执行
sudo snap install --classic code
3.vscode配置C++
3.1 直接在扩展中搜索C++安装即可
我安装了C++, Chinese, code runner, 安装都是同理
4.安装mysql
sudo apt update
sudo apt install mysql-server
sudo systemctl start mysql.service
安装好后, 需要对root修改密码
sudo mysql
执行后可以无密码进入
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
执行后可以修改密码,如果需要设置简单密码,需要把密码安全等级设置为low
// 如果需要远程连接, 需要把root用户权限范围改为%
5.vscode C++ 连接mysql
#include <stdio.h>
#include <iostream>
#include "mysql/mysql.h"using namespace std;int main()
{cout << "hello" << endl;MYSQL* mysql = mysql_init(NULL);if (mysql == NULL){printf("mysql init error;\n");return -1;}mysql = mysql_real_connect(mysql, "localhost", "root", "123456", "data", 0,NULL, 0);if (mysql == NULL){printf("mysql connect error \n");return -2;}printf("mysql api1 : %s\n", mysql_character_set_name(mysql));mysql_set_character_set(mysql, "utf8");printf("mysql api2 : %s\n", mysql_character_set_name(mysql));const char* sql = "select * from user";int ret = mysql_query(mysql, sql);if (ret != 0){printf("mysql_query failed! %s\n", mysql_error(mysql));return -1;}MYSQL_RES* res = mysql_store_result(mysql);if (res == NULL){printf("mysql_store_result failed! %s\n", mysql_error(mysql));return -1;}int num = mysql_num_fields(res);MYSQL_FIELD* fields = mysql_fetch_fields(res);for (int i = 0; i < num; i++){printf("%s\t\t", fields[i].name);}printf("\n");MYSQL_ROW row;while ((row = mysql_fetch_row(res)) != NULL){for (int i = 0; i < num; i++){printf("%s\t\t", row[i]);}printf("\n");}mysql_free_result(res);return 0;
}
这里我包含mysql头文件时候, 提示错误信息找不到mysql头文件
解决办法:
sudo apt-get install libmysqlclient-dev
编译文件时需要连接mysql的库
g++ main.cpp -o main -I /usr/include/mysql -L /usr/lib/x86_64-linux-gnu -lmysqlclient
测试成功, 操作细节不是很到位, 下次再装的时候, 再更新