采用connector-c++ 8.0操作数据库

1.下载最新的Connector

https://dev.mysql.com/downloads/connector/cpp/,下载带debug的库。

解压缩到本地,本次使用的是带debug模式的connector库:

注:其中mysqlcppconn与mysqlcppconn8的区别是:

2.在cmakelist中定义寻址头文件的路径与库的路径

复制代码
#定义头文件需要寻址的路径
include_directories(
    D:/Library/mysql-connector-c++-8.2.0-winx64/include/jdbc
)

#定义库文件需要寻址的路径
link_directories(
    D:/Library/mysql-connector-c++-8.2.0-winx64/lib64/vs14/debug
)

target_link_libraries(QtDemo2
        Qt5::Core
        Qt5::Gui
        Qt5::Widgets
        ......
        mysqlcppconn
)

3.复制对应的DLL到可执行目录

把D:\Library\mysql-connector-c+±8.2.0-winx64\lib64\debug中的mysqlcppconn-9-vs14.dll复制到项目的可执行目录下。

3.基础使用

https://dev.mysql.com/doc/connector-cpp/1.1/en/connector-cpp-examples-connecting.html

cpp 复制代码
#include "sql_connector.h"
#include "string"
#include <QDebug>

#include "mysql_connection.h"
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/prepared_statement.h"



void SqlConnector::process()
{
        qDebug("SqlConnector started....");


        std::string server = "tcp://localhost:3306";
        std::string username = "root";
        std::string password = "Xi1ozh#1";

        sql::Driver* driver;
        sql::Connection* connection;

        try
        {
                driver = get_driver_instance();
                connection = driver->connect(server, username, password);
                connection->setSchema("ws300");
        }
        catch (sql::SQLException e)
        {
                std::cout << "Could not connect to server. Error message: " << e.what() << "\n";
        }

        //查询
        sql::SQLString sql("select * from users;");
        std::unique_ptr<sql::Statement> statment(connection->createStatement());
        statment->execute("set names utf8mb4");
        std::unique_ptr<sql::ResultSet> result(statment->executeQuery(sql));
        while (result->next())
        {
                auto data = result->getString("password").asStdString();
                qDebug("SqlConnector username: %s", data.c_str());
        }

        result->close();
        statment->close();
        connection->close();
        delete connection;
        qDebug("SqlConnector finished....");
}
相关推荐
2401_8582861115 分钟前
CD27.【C++ Dev】类和对象(18)友元和内部类
开发语言·c++·类和对象
(王子变青蛙)17 分钟前
C++初始
开发语言·c++·程序人生
莫有杯子的龙潭峡谷17 分钟前
4.15 代码随想录第四十四天打卡
c++·算法
脑子慢且灵27 分钟前
MySQL:存储函数和存储过程
数据库·mysql·oracle·存储过程·存储函数
灋✘逞_兇33 分钟前
快速幂+公共父节点
数据结构·c++·算法·leetcode
是大强1 小时前
mongodb 远程访问
数据库·mongodb
双叶8361 小时前
(51单片机)LCD显示日期时间时钟(DS1302时钟模块教学)(LCD1602教程)
c语言·开发语言·数据库·单片机·嵌入式硬件·mongodb·51单片机
姜行运1 小时前
每日算法(双指针算法)(Day 1)
c++·算法·c#
Themberfue1 小时前
SQL ⑧-事务
数据库·sql·mysql
十五年专注C++开发1 小时前
面试题:请描述一下你在项目中是如何进行性能优化的?针对哪些方面进行了优化,采取了哪些具体的措施?
开发语言·数据结构·c++·qt·设计模式·性能优化