溫馨提示×

在c++中使用mysql庫的示例代碼解析

c++
小樊
89
2024-08-26 14:48:21
欄目: 云計(jì)算

在C++中使用MySQL庫可以通過MySQL Connector/C++庫來實(shí)現(xiàn)。下面是一個簡單的示例代碼,演示如何連接到MySQL數(shù)據(jù)庫,執(zhí)行查詢并獲取結(jié)果:

#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;
}

在這個示例代碼中,首先創(chuàng)建了一個MySQL連接并連接到指定的數(shù)據(jù)庫。然后創(chuàng)建了一個SQL語句對象并執(zhí)行了一個簡單的SELECT查詢。最后通過循環(huán)遍歷結(jié)果集并輸出每行數(shù)據(jù)中的列值。

需要注意的是,需要在代碼中替換相應(yīng)的用戶名、密碼、數(shù)據(jù)庫名稱、表名和列名,以及正確的數(shù)據(jù)庫連接地址。

另外,還需要確保安裝了MySQL Connector/C++庫,并在編譯時(shí)鏈接相應(yīng)的庫文件。可以參考MySQL Connector/C++的文檔來獲取更多詳細(xì)信息。

0