如何使用C 連接到MySQL 資料庫
在您的網站和MySQL 資料庫之間建立連接,並在上執行選擇查詢表行,您需要利用適當的C 庫。以下是實現此目標的方法:
導入以下庫:
<code class="cpp">#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;</code>
設定您的C 程序:
<code class="cpp">int main(void) { // Initialize connection details sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; try { // Establish connection to MySQL driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3306", "root", "root"); con->setSchema("test"); // Replace "test" with your database name // Create statement object stmt = con->createStatement(); // Execute select query res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // Display query results while (res->next()) { cout << "\t... MySQL replies: " << res->getString("_message") << endl; cout << "\t... MySQL says it again: " << res->getString(1) << endl; } // Clean up resources delete res; delete stmt; delete con; } catch (sql::SQLException &e) { // Handle database exception cout << "# ERR: SQLException in " << __FILE__ << endl; cout << "# ERR: " << e.what() << endl; } return EXIT_SUCCESS; }</code>
透過使用庫並按照以下步驟操作如上所述,您可以使用C 成功連線到MySQL 資料庫並對表格行執行選擇查詢。
以上是如何使用 C 連接到 MySQL 資料庫並執行查詢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!