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

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

相关推荐
银发控、4 小时前
MySQL联合索引
数据库·mysql
予枫的编程笔记4 小时前
【MySQL修炼篇】从踩坑到精通:事务隔离级别的3大异常(脏读/幻读/不可重复读)解决方案
数据库·mysql·后端开发·数据库事务·事务隔离级别·rr级别·脏读幻读不可重复读
碎梦归途5 小时前
思科网络设备配置命令大全,涵盖从交换机到路由器的核心配置命令
linux·运维·服务器·网络·网络协议·路由器·交换机
小天源5 小时前
nginx在centos7上热升级步骤
linux·服务器·nginx
AZ996ZA6 小时前
自学linux第十八天:【Linux运维实战】系统性能优化与安全加固精要
linux·运维·安全·性能优化
大虾别跑6 小时前
OpenClaw已上线:我的电脑开始自己打工了
linux·ai·openclaw
Bella的成长园地6 小时前
面试中关于 c++ async 的高频面试问题有哪些?
c++·面试
彷徨而立6 小时前
【C/C++】什么是 运行时库?运行时库 /MT 和 /MD 的区别?
c语言·c++
qq_417129256 小时前
C++中的桥接模式变体
开发语言·c++·算法
weixin_437044647 小时前
Netbox批量添加设备——堆叠设备
linux·网络·python