🗣 Wd提问: c++ mysql
🤖 Ai回答: I'll help you with C++ and MySQL integration、Here's a comprehensive guide on connecting C++ applications to MySQL databases.
MySQL C++ Connector Setup
Installation
Ubuntu/Debian:
bash
sudo apt-get install libmysqlclient-dev
sudo apt-get install libmysqlcppconn-dev
Windows:
Download MySQL Connector/C++ from Oracle's website
Or use vcpkg: `vcpkg install mysql-connector-cpp`
Basic Connection Example
cpp
include <mysql_driver.h
include <mysql_connection.h
include <cppconn/statement.h
include <cppconn/resultset.h
include <cppconn/exception.h
include <iostream
include <memory
int main() {
try {
// Create MySQL driver instance
sql::mysql::MySQL_Driver *driver = sql::mysql::get_mysql_driver_instance();
// Establish connection
std::unique_ptr<sql::Connection con(driver-connect(
tcp://127.0.0.1:3306, username, password));
// Connect to database
con-setSchema(your_database_name);
// Create statement
std::unique_ptr<sql::Statement stmt(con-createStatement());
// Execute query
std::unique_ptr<sql::ResultSet res(stmt-executeQuery(SELECT * FROM users));
// Process results
while (res-next()) {
std::cout << ID: << res-getInt(id)
<< , Name: << res-getString(name) << std::endl;
}
} catch (sql::SQLException &e) {
std::cout << MySQL Error: << e.what() << std::endl;
std::cout << Error Code: << e.getErrorCode() << std::endl;
std::cout << SQL State: << e.getSQLState() << std::endl;
}
return 0;
}
Prepared Statements Example
cpp
include <mysql_driver.h
include <mysql_connection.h
include <cppconn/prepared_statement.h
include <cppconn/resultset.h
include <iostream
class DatabaseManager {
private:
std::unique_ptr<sql::Connection connection;
public:
bool connect(const std::string& host, const std::string& user,
const std::string& password, const std::string& database) {
try {
sql::mysql::MySQL_Driver *driver = sql::mysql::get_mysql_driver_instance();
connection.reset(driver-connect(host, user, password));
connection-setSchema(database);
return true;
} catch (sql::SQLException &e) {
std::cerr << Connection failed: << e.what() << std::endl;
return false;
}
}
// Insert data using prepared statement
bool insertUser(const std::string& name, const std::string& email) {
try {
std::unique_ptr<sql::PreparedStatement pstmt(
connection-prepareStatement(INSERT INTO users(name, email) VALUES(?, ?)));
pstmt-setString(1, name);
pstmt-setString(2, email);
int rowsAffected = pstmt-executeUpdate();
return rowsAffected 0;
} catch (sql::SQLException &e) {
std::cerr << Insert failed: << e.what() << std::endl;
return false;
}
}
// Select data
void getUsers() {
try {
std::unique_ptr<sql::PreparedStatement pstmt(
connection-prepareStatement(SELECT id, name, email FROM users));
std::unique_ptr<sql::ResultSet res(pstmt-executeQuery());
while (res-next()) {
std::cout << ID: << res-getInt(id)
<< , Name: << res-getString(name)
<< , Email: << res-getString(email) << std::endl;
}
} catch (sql::SQLException &e) {
std::cerr << Query failed: << e.what() << std::endl;
}
}
// Update data
bool updateUser(int id, const std::string& name, const std::string& email) {
try {
std::unique_ptr<sql::PreparedStatement pstmt(
connection-prepareStatement(UPDATE users SET name=?, email=? WHERE id=?));
pstmt-setString(1, name);
pstmt-setString(2, email);
pstmt-setInt(3, id);
int rowsAffected = pstmt-executeUpdate();
return rowsAffected 0;
} catch (sql::SQLException &e) {
std::cerr << Update failed: << e.what() << std::endl;
return false;
}
}
// Delete data
bool deleteUser(int id) {
try {
std::unique_ptr<sql::PreparedStatement pstmt(
connection-prepareStatement(DELETE FROM users WHERE id=?));
pstmt-setInt(1, id);
int rowsAffected = pstmt-executeUpdate();
return rowsAffected 0;
} catch (sql::SQLException &e) {
std::cerr << Delete failed: << e.what() << std::endl;
return false;
}
}
};
int main() {
DatabaseManager db;
if (db.connect(tcp://127.0.0.1:3306, username, password, testdb)) {
std::cout << Connected successfully! << std::endl;
// Insert sample data
db.insertUser(John Doe, john@65.hk);
db.insertUser(Jane Smith, jane@65.hk);
// Display all users
std::cout << \nAll users: << std::endl;
db.getUsers();
// Update a user
db.updateUser(1, John Smith, johnsmith@65.hk);
// Delete a user
db.deleteUser(2);
} else {
std::cout << Failed to connect to database << std::endl;
}
return 0;
}
CMakeLists.txt for Building
cmake
cmake_minimum_required(VERSION 3.10)
project(MySQLCppProject)
set(CMAKE_CXX_STANDARD 14)
Find MySQL Connector/C++
find_package(PkgConfig REQUIRED)
pkg_check_modules(MYSQLCPPCONN REQUIRED mysqlcppconn)
Include directories
include_directories(${MYSQLCPPCONN_INCLUDE_DIRS})
Add executable
add_executable(main main.cpp)
Link libraries
target_link_libraries(main ${MYSQLCPPCONN_LIBRARIES})
Alternative: Using MySQL C API
cpp
include <mysql/mysql.h
include <iostream
include <string
class MySQLWrapper {
private:
MYSQL* connection;
public:
MySQLWrapper() : connection(nullptr) {}
~MySQLWrapper() {
if (connection) {
mysql_close(connection);
}
}
bool connect(const std::string& host, const std::string& user,
const std::string& password, const std::string& database) {
connection = mysql_init(nullptr);
if (!connection) {
std::cerr << mysql_init() failed << std::endl;
return false;
}
if (!mysql_real_connect(connection, host.c_str(), user.c_str(),
password.c_str(), database.c_str(), 0, nullptr, 0)) {
std::cerr << mysql_real_connect() failed: << mysql_error(connection) << std::endl;
return false;
}
return true;
}
bool executeQuery(const std::string& query) {
if (mysql_query(connection, query.c_str())) {
std::cerr << Query failed: << mysql_error(connection) << std::endl;
return false;
}
return true;
}
MYSQL_RES* getResult() {
return mysql_store_result(connection);
}
};
int main() {
MySQLWrapper db;
if (db.connect(localhost, username, password, testdb)) {
std::cout << Connected successfully! << std::endl;
// Execute a query
if (db.executeQuery(SELECT * FROM users)) {
MYSQL_RES* result = db.getResult();
if (result) {
MYSQL_ROW row;
int num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result))) {
for (int i = 0; i < num_fields; i++) {
std::cout << (row[i] ? row[i] : NULL) << ;
}
std::cout << std::endl;
}
mysql_free_result(result);
}
}
}
return 0;
}
Key Points to Remember
1、Error Handling: Always wrap database operations in try-catch blocks
2、Resource Management: Use smart pointers or RAII for automatic cleanup
3、Prepared Statements: Use for security against SQL injection
4、Connection Pooling: Consider implementing for high-performance applications
5、Thread Safety: MySQL connections are not thread-safe by default
Common Issues and Solutions
Linking Errors: Make sure to link against `mysqlcppconn` library
Connection Issues: Verify MySQL server is running and credentials are correct
Memory Leaks: Always free result sets and close connections
📣 商家广告 :
👍
0
👎
IP地址: 96.164.22.131
搜索次数: 0
提问时间: 2025-11-06 02:10:31
🛒 域名购买 :
827.net.cn 08.gold wg.gs 691.net.cn liuwang.com.cn 6.hn.cn 92.gs q-u.com.cn 875.net.cn y-u.com.cn
❓️ 热门提问 :
b2b2c网站建设 香港云主机排名 Semrush关键词本地SEO 自己建服务器 万网建站主机 国内个人用服务器 阿里ddos云防御 vue获取服务器ip 二级域名交易 云计算的新名词及含义 豌豆Ai站群搜索引擎系统
🌐 域名评估 :
byd.js.cn l.sn.cn musk.email yu7.hl.cn bb.hk.cn su.yn.cn b.xj.cn 8.sx.cn vivo.jl.cn ii.sn.cn
⛏ 最新挖掘 :
凯里酸汤鱼 贵阳烤脑花 都匀毛尖茶 花溪牛肉粉 贵阳烤生蚝 贵阳烤豆腐 贵阳纸包鱼 贵阳特色菜
🖌 热门作画 :
🤝 关于我们:
豌豆Ai
域名
建站
站群
留痕
推广
评估
源码
开发Ai
工具
日记
价格
加盟
广告
流量
留言
联系
🗨 加入群聊 :
🔗 友情链接 :
站群网站
Anonyma sökmotorer
ai提问
🧰 站长工具 :Ai工具 whois查询 搜索
📢 温馨提示 :本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
👉 技术支持 :本站由豌豆Ai 提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。