Home > Database > Mysql Tutorial > body text

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

Barbara Streisand
Release: 2024-10-27 00:16:31
Original
336 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!