在c++中使用mysql库的示例代码解析

c++
298
2024/8/26 15:32:05
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中使用MySQL库可以通过MySQL Connector/C++库来实现。下面是一个简单的示例代码,演示如何连接到MySQL数据库,执行查询并获取结果:

#include <iostream>
#include <mysql_connection.h>
#include <mysql_driver.h>
#include <mysql_error.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

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;
            cout << "Column2: " << res->getString(2) << endl;
            // Add more columns as needed
        }

        delete res;
        delete stmt;
        delete con;
    } catch (sql::SQLException &e) {
        cout << "# ERR: SQLException in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << "# ERR: " << e.what();
        cout << " (MySQL error code: " << e.getErrorCode();
        cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    }

    return 0;
}

在这个示例代码中,首先创建了一个MySQL连接并连接到指定的数据库。然后创建了一个SQL语句对象并执行了一个简单的SELECT查询。最后通过循环遍历结果集并输出每行数据中的列值。

需要注意的是,需要在代码中替换相应的用户名、密码、数据库名称、表名和列名,以及正确的数据库连接地址。

另外,还需要确保安装了MySQL Connector/C++库,并在编译时链接相应的库文件。可以参考MySQL Connector/C++的文档来获取更多详细信息。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++中bool类型函数返回值如何输出