推荐使用 MySQL 官方 Connector/C++ 连接数据库,它基于 JDBC 风格 API,支持面向对象操作、预处理语句、事务及 SSL,兼容 MySQL 5.7/8.0+;需安装对应开发包,正确配置路径,捕获 sql::SQLException 异常,并设置 utf8mb4 字符集防乱码。

要用 C++ 连接 MySQL 数据库,推荐使用官方提供的 MySQL Connector/C++(不是旧版的 Connector/C),它基于 JDBC 风格 API,支持面向对象操作,兼容 MySQL 5.7/8.0+,且支持预处理语句、事务、SSL 等特性。
确保已安装:
Linux(Ubuntu/Debian)可直接用 apt:
sudo apt update && sudo apt install libmysqlcppconn-dev
macOS(Homebrew):
立即学习“C++免费学习笔记(深入)”;
brew install mysql-connector-c++
Windows 建议下载 ZIP 包,解压后将 lib 和 include 路径加入项目配置(VS 中设置附加包含目录和附加库目录)。
以下是最简可用代码(需链接 mysqlcppconn 库):
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <iostream>
<p>int main() {
sql::Driver* driver = get_driver_instance();
std::unique_ptr<sql::Connection> conn(
driver->connect("tcp://127.0.0.1:3306", "root", "your_password")
);
conn->setSchema("testdb");</p><pre class='brush:php;toolbar:false;'>std::unique_ptr<sql::Statement> stmt(conn->createStatement());
std::unique_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT id, name FROM users"));
while (res->next()) {
std::cout << "ID: " << res->getInt("id")
<< ", Name: " << res->getString("name") << "\n";
}
return 0;}
编译命令(Linux/macOS 示例):
g++ -o demo demo.cpp -lmysqlcppconn
tcp://、unix://(本地 socket)、ssl://;也可写成 URL 形式:"mysqlx://user:pass@host:port/db"(仅限 X DevAPI,非本文 Connector/C++)sql::SQLException,建议用 try/catch 包裹关键操作std::unique_ptr 或 std::shared_ptr 管理 Connection/Statement/ResultSet,避免内存泄漏conn->setAutoCommit(false); conn->execute("SET NAMES utf8mb4");
使用 PreparedStatement 替代拼接字符串:
std::unique_ptr<sql::PreparedStatement> pstmt(
conn->prepareStatement("INSERT INTO users(name, age) VALUES (?, ?)")
);
pstmt->setString(1, "张三");
pstmt->setInt(2, 25);
pstmt->executeUpdate(); // 返回影响行数
注意:占位符是 ?,索引从 1 开始;类型方法如 setString、setDouble、setNull 等需严格匹配字段类型。
基本上就这些。不复杂但容易忽略异常处理和字符集设置,跑通第一步后,再逐步加事务、连接池(需自行封装或集成第三方如 cpptango 或 odb)也不难。
以上就是c++怎么连接MySQL数据库_c++ MySQL Connector/C++使用教程【数据库】的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号