在C++程序中,查詢mysql數據庫需要使用mysql C++ Connector庫。本文將介紹如何在main函數中連接mysql數據庫并進行簡單的查詢操作。
#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://localhost:3306", "root", "password"); con->setSchema("test"); // 創建查詢語句 stmt = con->createStatement(); res = stmt->executeQuery("SELECT * FROM student"); // 輸出查詢結果 while (res->next()) { cout<< "ID: "<< res->getInt("id")<< endl; cout<< "Name: "<< res->getString("name")<< endl; cout<< "Age: "<< res->getInt("age")<< endl; cout<< "Gender: "<< res->getString("gender")<< endl; cout<< endl; } } catch (sql::SQLException& e) { cout<< e.what()<< endl; } // 釋放資源 delete res; delete stmt; delete con; return 0; }
本文介紹了在C++程序中使用mysql C++ Connector庫查詢mysql數據庫的方法。首先,使用get_driver_instance函數獲取mysql驅動程序實例,然后使用connect函數連接數據庫。接著,創建查詢語句并使用executeQuery函數執行查詢,最后使用getInt、getString等函數獲取查詢結果。查詢完成后,需要釋放資源并關閉數據庫連接。