C++ 中如何把Point类型的二维数组加入MySQL数据库
时间: 2024-10-20 19:03:16 浏览: 22
在C++中将`Point`类型的二维数组插入到MySQL数据库,通常需要通过网络库(如MySQL Connector/C++)连接到数据库,并使用SQL语句来执行插入操作。以下是一个简化示例,假设`Point`结构包含两个元素(例如x和y坐标),并已包含了必要的库链接:
```cpp
#include <iostream>
#include <vector>
#include <mysql_connection.h>
#include <cppconn/driver.h>
// 假设Point结构体定义
struct Point {
int x;
int y;
};
void insertPointsToDatabase(std::vector<std::vector<Point>>& pointsArray, std::string host, std::string user, std::string password, std::string db) {
sql::Driver* driver;
sql::Connection* con = nullptr;
try {
// 初始化数据库连接
driver = sql::get_mysql_driver_instance();
con = driver->connect("tcp://" + host + "/", user, password);
// 创建准备语句
sql::Statement* stmt = con->createStatement();
std::string query = "INSERT INTO your_table (x, y) VALUES (?, ?)";
// 遍历二维数组并插入数据
for (const auto& row : pointsArray) {
for (const auto& point : row) {
stmt->execute(query, point.x, point.y);
}
}
// 关闭资源
delete stmt;
con->close();
} catch (sql::SQLException &e) {
std::cerr << "# ERR: SQLException in " << __FILE__ << ":" << __LINE__ << "\n";
std::cerr << "# ERR: " << e.what() << " (" << e.code << ")\n";
}
}
int main() {
// 示例二维点数组
std::vector<std::vector<Point>> points = {{1, 2}, {3, 4}, {5, 6}};
// 连接和插入到数据库
insertPointsToDatabase(points, "localhost", "your_username", "your_password", "your_database");
return 0;
}
```
阅读全文