linux C++ vscode连接mysql

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

cpp 复制代码
#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

测试成功, 操作细节不是很到位, 下次再装的时候, 再更新

相关推荐
ajassi20003 小时前
开源 C++ QT Widget 开发(十五)多媒体--音频播放
linux·c++·qt·开源
JosieBook4 小时前
【远程运维】Linux 远程连接 Windows 好用的软件:MobaXterm 实战指南
linux·运维·windows
文档搬运工4 小时前
Linux MInt启动速度的优化
linux
Broken Arrows4 小时前
Linux学习——管理网络安全(二十一)
linux·学习·web安全
雁于飞5 小时前
vscode中使用git、githup的基操
笔记·git·vscode·学习·elasticsearch·gitee·github
鹅毛在路上了5 小时前
C++, ffmpeg, libavcodec-RTSP拉流,opencv实时预览
c++·opencv·ffmpeg
Light605 小时前
领码方案|Linux 下 PLT → PDF 转换服务超级完整版:异步、权限、进度
linux·pdf·可观测性·异步队列·plt转pdf·权限治理·进度查询
福赖5 小时前
《MySQL基础——用户管理》
mysql·用户管理
John_ToDebug5 小时前
定制 ResourceBundle 的实现与 DuiLib 思想在 Chromium 架构下的应用解析
c++·chrome·ui
羚羊角uou5 小时前
【Linux】命名管道
linux·运维·服务器