How to connect to a MySQL database in C++?

In order to connect to a MySQL database in C++, you need to use the MySQL provided C API for operations. Below are the general steps to connect to a MySQL database:

  1. To install the MySQL C API library, you must first download and install it so that you can use MySQL functions and data types in C++. You can download either the binary distribution version or the source code from the MySQL official website.
  2. Include the necessary header files: In C++ programs, you need to include the MySQL header files to use MySQL functions and data types. For example, add the following line to your code:
#include <mysql.h>
  1. Establish a connection using mysql_real_connect()
MYSQL *conn;
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, "localhost", "user", "password", "database", 0, NULL, 0)) {
    fprintf(stderr, "%s\n", mysql_error(conn));
    exit(1);
}
  1. Execute a query in MySQL.
if (mysql_query(conn, "SELECT * FROM table")) {
    fprintf(stderr, "%s\n", mysql_error(conn));
    exit(1);
}
  1. store the result in MySQL
  2. Retrieve the next row from a MySQL result set.
MYSQL_RES *result;
MYSQL_ROW row;

result = mysql_store_result(conn);
while ((row = mysql_fetch_row(result))) {
    printf("%s\n", row[0]);
}

mysql_free_result(result);
  1. Close the MySQL connection.
mysql_close(conn);

This is a simple example demonstrating how to connect to MySQL and execute a query. You can modify and expand the code according to your own needs.

bannerAds