deC++与MYSQl链接
时间: 2024-03-21 21:41:11 浏览: 11
在 C++ 中使用 MySQL 数据库需要安装 MySQL Connector/C++,它是一个 C++ 的数据库驱动程序。以下是一个简单的 C++ 程序,用于连接 MySQL 数据库:
```c++
#include <iostream>
#include <mysql_connection.h>
#include <driver.h>
#include <exception.h>
#include <resultset.h>
#include <statement.h>
using namespace std;
int main() {
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* 创建连接 */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "username", "password");
/* 连接到数据库 */
con->setSchema("database_name");
/* 执行查询 */
stmt = con->createStatement();
res = stmt->executeQuery("SELECT * FROM table_name");
/* 处理结果 */
while (res->next()) {
cout << "ID: " << res->getInt("id") << endl;
cout << "Name: " << res->getString("name") << endl;
}
/* 关闭连接 */
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}
```
在此代码中,需要将 `username` 和 `password` 替换为 MySQL 数据库的用户名和密码,将 `database_name` 替换为要连接的数据库名称,将 `table_name` 替换为要查询的表名称。