VC(Visual C++)连接MySQL数据库通常涉及以下几个基础概念:
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/statement.h>
#include <cppconn/resultset.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/metadata.h>
#include <iostream>
int main() {
sql::mysql::MySQL_Driver *driver;
sql::Connection *con;
try {
// 创建MySQL驱动实例
driver = sql::mysql::get_mysql_driver_instance();
// 连接到数据库
con = driver->connect("tcp://127.0.0.1:3306", "username", "password");
// 选择数据库
con->setSchema("database_name");
// 执行查询
sql::Statement *stmt = con->createStatement();
sql::ResultSet *res = stmt->executeQuery("SELECT * FROM table_name");
// 处理结果集
while (res->next()) {
std::cout << res->getString("column_name") << std::endl;
}
// 清理资源
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
std::cerr << "SQL Error: " << e.what() << std::endl;
} catch (std::runtime_error &e) {
std::cerr << "Runtime Error: " << e.what() << std::endl;
}
return 0;
}
通过以上步骤和示例代码,你应该能够在VC++中成功连接并操作MySQL数据库。
领取专属 10元无门槛券
手把手带您无忧上云