阅读量:99
在C++中使用MySQL库可以通过MySQL Connector/C++库来实现。下面是一个简单的示例代码,演示如何连接到MySQL数据库,执行查询并获取结果:
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main() {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
try {
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 << "Column1: " << res>getString(1) << endl>getString(2) << endl>
在这个示例代码中,首先创建了一个MySQL连接并连接到指定的数据库。然后创建了一个SQL语句对象并执行了一个简单的SELECT查询。最后通过循环遍历结果集并输出每行数据中的列值。
需要注意的是,需要在代码中替换相应的用户名、密码、数据库名称、表名和列名,以及正确的数据库连接地址。
另外,还需要确保安装了MySQL Connector/C++库,并在编译时链接相应的库文件。可以参考MySQL Connector/C++的文档来获取更多详细信息。