"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Connect to a MySQL Database from Your C++ Application?

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

Posted on 2025-03-23
Browse:628

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:

    #include 
    #include 
    #include 
    #include 
  2. Create a Connection:

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

    con->setSchema("your_database_name");
  4. Create a Statement and Query:

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

    while (res->next()) {
      cout getString("column_name") 

Here's an example that demonstrates how to execute a simple "Hello World!" query:

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 getString("_message") 

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3