C++ MySQL 常用接口(基于 MySQL Connector/C++)

C++ MySQL 常用接口(基于 MySQL Connector/C++)

1. 数据库连接

接口:

cpp 复制代码
sql::mysql::MySQL_Driver *driver;
sql::Connection *con;

作用:

用于创建 MySQL 连接对象。

示例:

cpp 复制代码
driver = sql::mysql::get_mysql_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "user", "password");

释放资源:

cpp 复制代码
delete con;

2. 选择数据库

接口:

cpp 复制代码
con->setSchema("database_name");

作用:

指定要操作的数据库。

示例:

cpp 复制代码
con->setSchema("test_db");

3. 创建 SQL 语句对象

接口:

cpp 复制代码
sql::Statement *stmt;
stmt = con->createStatement();

作用:

创建一个 SQL 语句执行对象。

示例:

cpp 复制代码
stmt = con->createStatement();
stmt->execute("CREATE TABLE IF NOT EXISTS users (id INT, name VARCHAR(50))");
delete stmt;

4. 执行 SQL 语句

接口:

cpp 复制代码
stmt->execute("SQL语句");
stmt->executeQuery("SQL查询语句");
stmt->executeUpdate("SQL更新语句");

作用:

  • execute() 用于执行不返回结果集的 SQL 语句(如 CREATE TABLE)。
  • executeQuery() 用于执行 SELECT 查询,返回 ResultSet 结果集。
  • executeUpdate() 用于 INSERT、UPDATE、DELETE,返回影响的行数。

示例:

cpp 复制代码
stmt = con->createStatement();
stmt->execute("INSERT INTO users (id, name) VALUES (1, 'Tom')");
sql::ResultSet *res = stmt->executeQuery("SELECT * FROM users");
int rows = stmt->executeUpdate("UPDATE users SET name='Jerry' WHERE id=1");

delete res;
delete stmt;

5. 获取查询结果

接口:

cpp 复制代码
sql::ResultSet *res;
res->next();
res->getInt("column_name");
res->getString("column_name");

作用:

获取查询结果,并读取列值。

示例:

cpp 复制代码
sql::ResultSet *res = stmt->executeQuery("SELECT * FROM users");
while (res->next()) {
    std::cout << "ID: " << res->getInt("id") << ", Name: " << res->getString("name") << std::endl;
}
delete res;

6. 使用预处理语句

接口:

cpp 复制代码
sql::PreparedStatement *pstmt;
pstmt = con->prepareStatement("SQL语句");
pstmt->setInt(参数索引, 整数值);
pstmt->setString(参数索引, 字符串值);
pstmt->execute();
pstmt->executeQuery();
pstmt->executeUpdate();

作用:

  • prepareStatement() 预编译 SQL,提高执行效率并防止 SQL 注入。
  • setInt() / setString() 设置 SQL 语句中的参数值。

示例:

cpp 复制代码
sql::PreparedStatement *pstmt = con->prepareStatement("INSERT INTO users (id, name) VALUES (?, ?)");
pstmt->setInt(1, 2);
pstmt->setString(2, "Alice");
pstmt->executeUpdate();
delete pstmt;

7. 事务处理
自动提交(Auto Commit)

MySQL 默认启用 Auto Commit ,每条 INSERT、UPDATE、DELETE 语句都会 立即生效,即使程序崩溃,数据也已经修改了。

示例(默认自动提交)

cpp 复制代码
sql::Statement *stmt = con->createStatement();
stmt->execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
delete stmt;  // 即使程序崩溃,数据库的修改依然有效
手动事务(关闭自动提交)

如果希望多个 SQL 语句 全部成功或全部失败 ,需要 关闭自动提交 并手动 COMMIT 或 ROLLBACK。

接口:

cpp 复制代码
con->setAutoCommit(false);
con->commit();
con->rollback();

作用:

  • setAutoCommit(false):关闭自动提交,进入事务模式。
  • commit():提交事务,所有 SQL 语句的更改生效。
  • rollback():回滚事务,撤销所有未提交的更改。

示例(手动控制事务)

cpp 复制代码
try {
    con->setAutoCommit(false); // 关闭自动提交,开启事务模式

    sql::PreparedStatement *pstmt = con->prepareStatement("UPDATE accounts SET balance = balance - ? WHERE id = ?");
    pstmt->setDouble(1, 100.0);
    pstmt->setInt(2, 1);
    pstmt->executeUpdate();
    delete pstmt;

    pstmt = con->prepareStatement("UPDATE accounts SET balance = balance + ? WHERE id = ?");
    pstmt->setDouble(1, 100.0);
    pstmt->setInt(2, 2);
    pstmt->executeUpdate();
    delete pstmt;

    con->commit();  // **手动提交事务,所有修改一起生效**
} catch (sql::SQLException &e) {
    con->rollback();  // **出错时回滚,保证数据一致性**
    std::cerr << "Transaction failed: " << e.what() << std::endl;
}
事务的使用场景

适用于需要保证 数据一致性 的情况:

  • 银行转账(A 账户扣钱,B 账户加钱,必须同时成功)
  • 库存管理(购买商品时,需要同时更新库存和订单信息)
  • 订单处理(下单时,必须同时修改多个表的数据)

总结

  • MySQL 默认 Auto Commit = true,每条 SQL 语句都会立即提交。
  • 关闭 Auto Commit 后,可以 手动提交或回滚,确保数据一致性。
  • 使用 commit() 确保更改生效,使用 rollback() 处理失败情况。

8. 关闭连接

接口:

cpp 复制代码
delete res;
delete stmt;
delete pstmt;
delete con;

作用:

释放资源,避免内存泄漏。

示例:

cpp 复制代码
delete res;
delete stmt;
delete pstmt;
delete con;

总结

类别 接口 作用
数据库连接 sql::mysql::MySQL_Driver *driver; sql::Connection *con; driver = sql::mysql::get_mysql_driver_instance(); con = driver->connect(...); 连接 MySQL 数据库
选择数据库 con->setSchema("database_name"); 选择数据库
执行 SQL stmt->execute("SQL语句"); stmt->executeQuery("SQL查询语句"); stmt->executeUpdate("SQL更新语句"); 执行 SQL 语句
获取查询结果 res->next(); res->getInt("column_name"); res->getString("column_name"); 获取查询结果
预处理语句 pstmt = con->prepareStatement("SQL语句"); pstmt->setInt(1, value); pstmt->setString(2, "value"); pstmt->executeUpdate(); 预编译 SQL,防止 SQL 注入
事务管理 con->setAutoCommit(false); con->commit(); con->rollback(); 控制事务提交和回滚
释放资源 delete res; delete stmt; delete pstmt; delete con; 释放内存,避免泄漏

代码示例

cpp 复制代码
/* Copyright 2008, 2010, Oracle and/or its affiliates.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.

There are special exceptions to the terms and conditions of the GPL
as it is applied to this software. View the full text of the
exception in file EXCEPTIONS-CONNECTOR-C++ in the directory of this
software distribution.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

/*
  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Let's have MySQL count from 10 to 1..." << endl;

try {
  sql::Driver *driver;
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;
  sql::PreparedStatement *pstmt;

  /* Create a connection */
  driver = get_driver_instance();
  con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
  /* Connect to the MySQL test database */
  con->setSchema("test");

  stmt = con->createStatement();
  stmt->execute("DROP TABLE IF EXISTS test");
  stmt->execute("CREATE TABLE test(id INT)");
  delete stmt;

  /* '?' is the supported placeholder syntax */
  pstmt = con->prepareStatement("INSERT INTO test(id) VALUES (?)");
  for (int i = 1; i <= 10; i++) {
    pstmt->setInt(1, i);
    pstmt->executeUpdate();
  }
  delete pstmt;

  /* Select in ascending order */
  pstmt = con->prepareStatement("SELECT id FROM test ORDER BY id ASC");
  res = pstmt->executeQuery();

  /* Fetch in reverse = descending order! */
  res->afterLast();
  while (res->previous())
    cout << "\t... MySQL counts: " << res->getInt("id") << endl;
  delete res;

  delete pstmt;
  delete con;

} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line " >>
     << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << >>
     " )" << endl;
}

cout << endl;

return EXIT_SUCCESS;
}
相关推荐
xiaoye-duck14 分钟前
《C++ 项目:手写大模型接入 SDK》LLMManager架构设计与实现
开发语言·网络·c++·语言模型
一条大祥脚37 分钟前
CuTe 与 CuTe DSL:从 C++ 模板元编程到 Python DSL 的 GPU 编程演进
开发语言·c++·python·cutlass·cute·cute dsl
·present·1 小时前
CSAPP(lecture 13_02 Linking)
c语言·c++
FRing031 小时前
vue2干货总结8(路由模块封装、router-link、声明式导航、路由重定向、编程式导航)
开发语言·前端·vue.js·vue2
旖旎夜光1 小时前
【C++ 基础入门】C++ 多态(上):虚函数、重写、override/final 与抽象类
开发语言·c++·笔记·学习
aiks_yuan1 小时前
MySQL 深分页 LIMIT 越翻越慢怎么办:300 万行实测 OFFSET、延迟关联和 keyset 的耗时差距(MySQL 8.2)
mysql
Decay__2 小时前
14_MySQL 高可用与容灾架构 —— MGR / InnoDB Cluster / Keepalived+VIP / 双主 / 读写分离 / 两地三中心
运维·数据库·sql·mysql·架构
starzy19902 小时前
深入理解Scala嵌套函数:作用域封装之道
开发语言·scala
Sakura_j_h_2 小时前
从零写一个 MCP stdio Server:用 Python 校验博客文章格式
开发语言·python·自动化·ai工具·mcp·json-rpc
青少儿编程课堂3 小时前
蓝桥杯青少组图形化 STEMA 省考(报名倒计时·11/22开考)+ 全国青少年信息素养大赛 2026—2027赛季 + 电子学会图形化考级:校园华容道大闯关
c++·python·算法·bfs·信息学竞赛