首頁  >  文章  >  資料庫  >  如何從 C 應用程式連接到 MySQL 資料庫?

如何從 C 應用程式連接到 MySQL 資料庫?

Barbara Streisand
Barbara Streisand原創
2024-10-26 13:47:30192瀏覽

How to Connect to a MySQL Database from Your C   Application?

如何使用 C 連接 MySQL 資料庫

從 C 應用程式連接到 MySQL 資料庫可讓您執行資料庫操作,例如執行 SQL 查詢。以下是如何操作的指南:

先決條件:

  • 安裝 MySQL Connector/C 函式庫。

步驟:

  1. 包含必要的標頭:

    <code class="cpp">#include <cppconn/driver.h>
    #include <cppconn/exception.h>
    #include <cppconn/resultset.h>
    #include <cppconn/statement.h></code>
  2. 包含必要的標頭:
  3. <code class="cpp">sql::Driver *driver = get_driver_instance();
    sql::Connection *con = driver->connect("tcp://127.0.0.1:3306", "root", "root");</code>
  4. 創建連接:
  5. <code class="cpp">con->setSchema("your_database_name");</code>
  6. 設置數據庫:
  7. <code class="cpp">sql::Statement *stmt = con->createStatement();
    sql::ResultSet *res = stmt->executeQuery("your_sql_query");</code>
  8. 建立語句與查詢:
  9. <code class="cpp">while (res->next()) {
      cout << res->getString("column_name") << endl;
    }
  10. 迭代結果:

<code class="cpp">int main() {
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;

  try {
    con = get_driver_instance()->connect(
        "tcp://127.0.0.1:3306", "user", "password");
    con->setSchema("test");

    stmt = con->createStatement();
    res = stmt->executeQuery("SELECT 'Hello World!' AS _message");

    while (res->next()) {
      cout << "MySQL replies: " << res->getString("_message") << endl;
    }
  } catch (sql::SQLException &amp;e) {
    cout << "MySQL error code: " << e.getErrorCode() << endl;
  }

  return 0;
}</code>
迭代結果:

迭代結果>這是一個範例示範如何執行簡單的「Hello World!」 query:依照下列步驟,您可以連線到MySQL 資料庫並使用C 執行SQL 查詢。

以上是如何從 C 應用程式連接到 MySQL 資料庫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn