- 环境配置
- Connection.h
- Connection.cpp
- 运行示例
由于是在 virtual studio 2022上开发,若要使用到MySQL自带的库,需要配置环境。
- 打开解决方案,右键点击项目名称
在弹出页面点击最下面的属性。
找到MySQL的mysql.h的include路径,复制该路径
复制到刚打开的属性页面里的 【C/C++】 =》选择【常规】=》在【附加包含目录】后面粘贴路径。
- 找到.lib的路径,复制该路径
粘贴到 【链接器】=》【常规】=》【附加库目录】
- 将lib下面的libmysql.dll复制到自己的项目下
再去属性里选择【链接器】、【输入】、【附加依赖项】、加入这个库的名字。
#pragma once // 实现MySQL数据库的操作 #includeConnection.cpp#include using namespace std; // 数据库操作类 class Connection { public: // 初始化数据库连接 Connection(); // 释放数据库连接资源 ~Connection(); // 连接数据库 bool connect(string ip, unsigned short port, string user, string password, string dbname); // 更新操作 insert、delete、update bool update(string sql); // 查询操作 select MYSQL_RES* query(string sql); private: MYSQL* _conn; // 表示和MySQL Server的一条连接 };
#include运行示例#include #include "Connection.h" #include "public.h" using namespace std; // 初始化数据库连接 Connection::Connection() { _conn = mysql_init(nullptr); } // 释放数据库连接资源 Connection::~Connection() { if (_conn != nullptr) mysql_close(_conn); } // 连接数据库 bool Connection::connect(string ip, unsigned short port, string user, string password, string dbname) { MYSQL* p = mysql_real_connect(_conn, ip.c_str(), user.c_str(), password.c_str(), dbname.c_str(), port, nullptr, 0); return p != nullptr; } // 更新操作 insert、delete、update bool Connection::update(string sql) { if (mysql_query(_conn, sql.c_str())) { LOG("更新失败:" + sql); return false; } return true; } // 查询操作 select MYSQL_RES* Connection::query(string sql) { if (mysql_query(_conn, sql.c_str())) { LOG("查询失败:" + sql); return nullptr; } return mysql_use_result(_conn); }
执行一个插入的语句:
#define _CRT_SECURE_NO_WARNINGS #include#include "Connection.h" using namespace std; int main(void) { Connection conn; char sql[1024] = { 0 }; sprintf(sql, "insert into user(id, name, age, sex) values(%d, '%s', %d, '%s')", 1, "zhangsan", 20, "male"); conn.connect("127.0.0.1", 3306, "root", "123456", "chat"); conn.update(sql); return 0; }
MySQL插入成功



