c++ sql::Connection 指明用什么database
时间: 2024-03-11 12:48:28 浏览: 9
您好,使用 C++ 连接 MySQL 数据库时,可以通过在连接字符串中指定数据库名来指明使用哪个数据库:
```c++
#include <iostream>
#include <mysql_driver.h>
#include <mysql_connection.h>
using namespace std;
using namespace sql;
int main() {
// 创建 MySQL 连接
Driver* driver = get_driver_instance();
Connection* con = driver->connect("tcp://127.0.0.1:3306/db_name", "user_name", "password");
// 执行 SQL 查询等操作
// 关闭连接
con->close();
delete con;
return 0;
}
```
在上述代码中,连接字符串 `"tcp://127.0.0.1:3306/db_name"` 中的 `db_name` 即为指定的数据库名。您需要将 `user_name` 和 `password` 替换为您自己的用户名和密码。
当然,您也可以在连接后使用 `USE` 命令来选择要操作的数据库:
```c++
// 连接 MySQL,指定默认数据库名
Connection* con = driver->connect("tcp://127.0.0.1:3306", "user_name", "password");
con->setSchema("db_name"); // 选择要操作的数据库
```
此时连接字符串中只需要指定 MySQL 服务器地址和端口号,不需要指定数据库名。然后在连接后使用 `setSchema` 方法来选择要操作的数据库。