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

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

相关推荐
Roc-xb3 分钟前
解决Ubuntu22.04 安装vmware tools之后,不能实现文件复制粘贴和拖拽问题
linux·ubuntu22.04·vmvare
JANYI20185 分钟前
一文读懂-嵌入式Ubuntu平台
linux·运维·ubuntu
admiraldeworm6 分钟前
Mysql、Oracle、Sql Server、达梦之间sql的差异
mysql·oracle·sqlserver·达梦
ha204289419411 分钟前
c++学习之--- list
c语言·c++·学习·list
君鼎42 分钟前
muduo库TcpServer模块详解
linux·网络·c++
卡戎-caryon1 小时前
【MySQL】02.数据库基础
linux·网络·数据库·mysql·存储引擎
ZHOU_WUYI1 小时前
React与Docker中的MySQL进行交互
mysql·react.js·docker
龙湾开发2 小时前
轻量级高性能推理引擎MNN 学习笔记 03.在iOS运行MNN的示例
c++·学习·ios·图形渲染·mnn
无敌的牛2 小时前
Linux梦开始的地方
linux·运维·服务器
苹果酱05672 小时前
React方向:react脚手架的使用
java·vue.js·spring boot·mysql·课程设计