C++连接数据库

个人笔记,留给n年后的自己
引用:https://www.bilibili.com/video/BV1m24y1a79o
要学看这个,文章给我自己看的

1.安装Connector/C++

下载地址:https://dev.mysql.com/downloads/connector/cpp/
官方文档:https://dev.mysql.com/doc/connector-cpp/8.0/en/preface.html

2.VS配置

include的目录(需要mysql目录下的include)
C++连接数据库_第1张图片

lib目录
C++连接数据库_第2张图片

dll依赖(需要加到项目目录下)
C++连接数据库_第3张图片

3.代码

初始化mysql连接(后面会封装到类里)

#pragma once
#include
#include
#include
#include
#include

const char* host = "127.0.0.1";
const char* user = "root";
const char* password = ;
const char* database = "genshin";
const int port = 3306;


MYSQL* con;
con = mysql_init(NULL);
//设置字符编码
mysql_options(con, MYSQL_SET_CHARSET_NAME, "GBK");
if (!mysql_real_connect(con, host, user, password, database, port, NULL, 0))
{
    fprintf(stderr, "failed to connect to database: Error:", mysql_error(con));
    return;
}

mysql_close(con);

增删改查

char sql[256];
    //增
    //sprintf_s(sql, "insert into forniture(name,paid,area,model,sorted,material)"
        //" values('%s','%s','%s','%s','%s','%s')",
        //forn->name.c_str(), forn->paid.c_str(), forn->area.c_str(),
        //forn->model.c_str(), forn->sorted.c_str(), forn->material.c_str());

    //删
    //sprintf_s(sql,"delete from table_name where xx=xx");

    //改
    //sprintf_s(sql,"update table_name set qq='123456' where id=5;");
    
    //查
    /*T str;
    sprintf_s(sql, "select xxx from table_name where xx=xx");
    MYSQL_RES* res = mysql_store_result(con);
    MYSQL_ROW row;
    while (row = mysql_fetch_row(res))
    {

    }*/

    //执行
    //执行失败(就是下面这样,不用加!)
    //if(mysql_query(con, sql))
    {
      //执行失败所需要输出的内容
    };

4.集成到类里

class mysql_manager
{
public:
    mysql_manager();//初始化连接
    ~mysql_manager();//关闭连接
    void insert_sql();
    void delete_sql();
    void update_sql();
    void select_sql();
public:
  //单例模式(不懂,但看着好好用,回头研究)
    static mysql_manager GetInstance()
    {
        static mysql_manager Mysql_m;
        return Mysql_m;
    }
private:
    MYSQL* con;
    void sample_sql(); //存放增删改查示例代码(上面)
    const char* host = "127.0.0.1";
    const char* user = "root";
    const char* password = ;
    const char* database = "test";
    const int port = 3306;
};

你可能感兴趣的:(数据库,c++,mysql,sql)