Home  >  Article  >  Database  >  How to Connect to a MySQL Database from Your C Application?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 13:47:30289browse

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

How to Connect MySQL Database Using C

Connecting to a MySQL database from a C application allows you to perform database operations, such as executing SQL queries. Here's a guide on how to do it:

Prerequisites:

  • Install the MySQL Connector/C libraries.

Steps:

  1. Include Necessary Headers:

    <code class="cpp">#include <cppconn/driver.h>
    #include <cppconn/exception.h>
    #include <cppconn/resultset.h>
    #include <cppconn/statement.h></code>
  2. Create a Connection:

    <code class="cpp">sql::Driver *driver = get_driver_instance();
    sql::Connection *con = driver->connect("tcp://127.0.0.1:3306", "root", "root");</code>
  3. Set the Database:

    <code class="cpp">con->setSchema("your_database_name");</code>
  4. Create a Statement and Query:

    <code class="cpp">sql::Statement *stmt = con->createStatement();
    sql::ResultSet *res = stmt->executeQuery("your_sql_query");</code>
  5. Iterate Over Results:

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

Here's an example that demonstrates how to execute a simple "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>

By following these steps, you can connect to a MySQL database and execute SQL queries using C .

The above is the detailed content of How to Connect to a MySQL Database from Your C Application?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn