在C++中创建MySQL数据库需要使用MySQL Connector/C++,下面是一个简单的示例代码:
#include <iostream>
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main() {
try {
sql::Driver* driver = get_driver_instance();
// MySQL连接参数
string url("tcp://localhost:3306");
string user("root");
string password("password");
// 获取连接
sql::Connection* conn = driver->connect(url, user, password);
// 创建数据库
sql::Statement* stmt = conn->createStatement();
stmt->execute("CREATE DATABASE mydb");
delete stmt;
delete conn;
cout << "Database created successfully." << endl;
} catch (sql::SQLException& e) {
cout << "SQL Exception: " << e.what() << endl;
}
return 0;
}
注意:此代码仅适用于本地MySQL服务器。如果您需要连接远程服务器,则需要更改连接参数中的主机名和端口号。