使用 C 連接到 MySQL 資料庫
為了建立與 MySQL 資料庫的連接並執行查詢,C 提供了全面的解決方案。讓我們探討如何有效率地完成此任務。
所需的函式庫
先將必要的函式庫合併到您的C 專案中:
cppconn/statement.h
cppconn/statement.h<code class="c++">#include <stdlib.h> #include <iostream> #include "mysql_connection.h" #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> using namespace std; int main() { try { // Create the necessary objects sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; // Establish a connection driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3306", "root", "root"); // Set the default schema con->setSchema("test"); // Create a statement object stmt = con->createStatement(); // Execute a query res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // Replace with your statement // Iterate over the results while (res->next()) { cout << "\t... MySQL replies: "; // Access column data by alias or column name cout << res->getString("_message") << endl; cout << "\t... MySQL says it again: "; // Access column data by numeric offset (1-based) cout << res->getString(1) << endl; } // Clean up resources delete res; delete stmt; delete con; } catch (sql::SQLException &e) { // Handle exceptions cout << "# ERR: SQLException in " << __FILE__ << " (" << __FUNCTION__ << ") on line " << __LINE__ << endl; cout << "# ERR: " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )" << endl; } return EXIT_SUCCESS; }</code>
cppconn/statement.h
cppconn/statement.h
:允許建立和執行SQL 語句範例程式碼以下範例程式碼示範如何建立連接,執行查詢,並從MySQL 資料庫擷取結果: 結論按照以下步驟並結合提供的程式碼範例,您可以成功連接到從C 語言建立您的MySQL 資料庫,執行查詢並檢索所需的結果。這使您能夠開發健壯且高效的資料庫驅動應用程式。以上是如何使用 C 連線到 MySQL 資料庫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!