首页  >  文章  >  数据库  >  如何从 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. 创建连接:

    <code class="cpp">sql::Driver *driver = get_driver_instance();
    sql::Connection *con = driver->connect("tcp://127.0.0.1:3306", "root", "root");</code>
  3. 设置数据库:

    <code class="cpp">con->setSchema("your_database_name");</code>
  4. 创建语句和查询:

    <code class="cpp">sql::Statement *stmt = con->createStatement();
    sql::ResultSet *res = stmt->executeQuery("your_sql_query");</code>
  5. 迭代结果:

    <code class="cpp">while (res->next()) {
      cout << res->getString("column_name") << endl;
    }

这是一个示例演示如何执行简单的“Hello World!” query:

<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>

按照以下步骤,您可以连接到 MySQL 数据库并使用 C 执行 SQL 查询。

以上是如何从 C 应用程序连接到 MySQL 数据库?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn