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

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

相关推荐
Nebula嵌入式4 小时前
【C语言】09-深入解析main函数
linux·c语言·开发语言·嵌入式
Dxy12393102165 小时前
Linux 编译安装 Python 3.12.10(多版本共存,不破坏系统Python)
linux·运维·python
xz驱动分享7 小时前
Linux DMA 子系统学习笔记
linux·dma·rk3588·嵌入式软件
888CC++7 小时前
C语言与C++的区别:从面向过程到面向对象
java·c语言·c++
w67820078 小时前
Prisma不能优雅的支持DTO,试试Vona ORM吧
linux·运维·ubuntu
Darkwanderor8 小时前
Linux系统编程实战项目:模拟实现shell
linux·c++
himobrinehacken8 小时前
揭秘Windows程序启动的神秘之旅
c++·安全
库玛西9 小时前
C++ 运行时多态 :核心总结与原理图解
c语言·c++·笔记
杨某不才10 小时前
如何能让Linux服务器对shell 终端 + sftp 文件传输长期保活
linux·运维·服务器
vance0410 小时前
免费Cloudflare隧道隐藏公网IP
linux·tcp/ip·github