Home  >  Article  >  Database  >  How to Connect to a MySQL Database and Execute Queries Using C ?

How to Connect to a MySQL Database and Execute Queries Using C ?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 00:16:31337browse

How to Connect to a MySQL Database and Execute Queries Using C  ?

How to Connect to a MySQL Database using C

To establish a connection between your website and a MySQL database, and execute select queries on table rows, you'll need to utilize the appropriate C libraries. Here's how you can achieve this:

Import the following libraries:

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

Set up your C program:

<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 &amp;e) {
    // Handle database exception
    cout << "# ERR: SQLException in " << __FILE__ << endl;
    cout << "# ERR: " << e.what() << endl;
  }

  return EXIT_SUCCESS;
}</code>

By utilizing the libraries and following the steps outlined above, you can successfully connect to a MySQL database using C and execute select queries on table rows.

The above is the detailed content of How to Connect to a MySQL Database and Execute Queries Using C ?. 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