Connecting C Programs to MariaDB: A Step-by-Step Guide

2024-07-27

  • MariaDB: A popular open-source relational database management system (RDBMS) known for its compatibility with MySQL. It's widely used for storing, managing, and retrieving data in various applications.
  • C: A general-purpose programming language renowned for its efficiency and control over system resources. It's often used for creating low-level applications that interact with databases like MariaDB.

Connecting C Programs to MariaDB

To enable C programs to interact with MariaDB, you'll need a library called the MariaDB Connector/C. This library provides functions and structures that simplify tasks like:

  • Establishing Connections: You can initiate a connection to a MariaDB server by specifying connection details like hostname, port number, username, and password.
  • Executing SQL Statements: The connector allows you to write SQL queries within your C code to perform operations on the database, such as selecting, inserting, updating, or deleting data.
  • Processing Results: After executing queries, you can retrieve and process the results returned by the database. The connector provides mechanisms to fetch data row by row, handle different data types, and manage memory allocation effectively.
  • Closing Connections: When you're done interacting with the database, it's important to properly close the connection to release resources and avoid potential issues.

Steps for Using MariaDB in C:

  1. Include Necessary Headers: Incorporate the MariaDB Connector/C header files in your C program using #include directives.
  2. Initialize the Connector: Call the mysql_library_init() function to set up the connector library and ensure it's ready for use.
  3. Establish a Connection: Employ the mysql_real_connect() function to create a connection to the MariaDB server, providing the required connection parameters.
  4. Execute SQL Statements: Utilize functions like mysql_query() to send SQL queries to the database.
  5. Process Results (if applicable): If your query retrieves data, employ functions like mysql_store_result() to capture the results and then iterate through them using mysql_fetch_row(). Extract data from each row using appropriate functions based on the data types (e.g., mysql_fetch_string(), mysql_fetch_int()).
  6. Close the Connection: When finished, call mysql_close() to terminate the connection and free allocated resources.
  7. Cleanup (optional): Call mysql_library_end() to clean up any remaining resources associated with the connector library, though this is often handled automatically upon program termination.

Example Code (illustrative):

#include <mysql.h>  // MariaDB Connector/C header

int main() {
    MYSQL *conn;  // Pointer to the MySQL connection object

    // Initialize the connector
    mysql_library_init(NULL, NULL);

    // Connection details (replace with your actual values)
    const char *server = "localhost";
    const char *user = "your_username";
    const char *password = "your_password";
    const char *database = "your_database";

    // Connect to the MariaDB server
    conn = mysql_real_connect(conn, server, user, password, database, 0, NULL, 0);

    if (conn) {
        printf("Connected to MariaDB server\n");

        // Sample SQL query (replace with your desired query)
        const char *query = "SELECT * FROM your_table";

        // Execute the query
        if (mysql_query(conn, query) != 0) {
            fprintf(stderr, "Error executing query: %s\n", mysql_error(conn));
        } else {
            MYSQL_RES *result = mysql_store_result(conn);  // Get results

            if (result) {
                int num_fields = mysql_num_fields(result);  // Number of columns
                MYSQL_ROW row;

                // Process each row
                while ((row = mysql_fetch_row(result)) != NULL) {
                    for (int i = 0; i < num_fields; i++) {
                        printf("%s ", row[i]);  // Access data in each column
                    }
                    printf("\n");
                }

                mysql_free_result(result);  // Free result memory
            }
        }

        mysql_close(conn);  // Close the connection
        printf("Connection closed\n");
    } else {
        fprintf(stderr, "Failed to connect to MariaDB: %s\n",



#include <mysql.h>

int main() {
    MYSQL *conn;

    // Initialize the connector
    mysql_library_init(NULL, NULL);

    // Connection details (replace with your actual values)
    const char *server = "localhost";
    const char *user = "your_username";
    const char *password = "your_password";

    // Connect to the MariaDB server
    conn = mysql_real_connect(conn, server, user, password, NULL, 0, NULL, 0);

    if (conn) {
        printf("Connected to MariaDB server\n");

        // Get server version information
        MYSQL_FIELD *field;
        MYSQL_RES *result = mysql_query(conn, "SELECT VERSION()");

        if (result) {
            field = mysql_fetch_field(result);
            printf("Server version: %s\n", mysql_fetch_row(result)[0]);
            mysql_free_result(result);
        } else {
            fprintf(stderr, "Error executing query: %s\n", mysql_error(conn));
        }

        mysql_close(conn);
        printf("Connection closed\n");
    } else {
        fprintf(stderr, "Failed to connect to MariaDB: %s\n", mysql_error(conn));
    }

    mysql_library_end();  // Cleanup (optional)

    return 0;
}

Creating a Table and Inserting Data:

#include <mysql.h>

int main() {
    MYSQL *conn;

    // Initialize the connector
    mysql_library_init(NULL, NULL);

    // Connection details (replace with your actual values)
    const char *server = "localhost";
    const char *user = "your_username";
    const char *password = "your_password";
    const char *database = "your_database";

    // Connect to the MariaDB server
    conn = mysql_real_connect(conn, server, user, password, database, 0, NULL, 0);

    if (conn) {
        printf("Connected to MariaDB server\n");

        // Create a table (replace with your desired table structure)
        const char *create_table = "CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255))";
        if (mysql_query(conn, create_table) != 0) {
            fprintf(stderr, "Error creating table: %s\n", mysql_error(conn));
        } else {
            printf("Table created (if it didn't exist)\n");

            // Insert data (replace with your values)
            const char *insert_data = "INSERT INTO users (name) VALUES ('John Doe')";
            if (mysql_query(conn, insert_data) != 0) {
                fprintf(stderr, "Error inserting data: %s\n", mysql_error(conn));
            } else {
                printf("Data inserted\n");
            }
        }

        mysql_close(conn);
        printf("Connection closed\n");
    } else {
        fprintf(stderr, "Failed to connect to MariaDB: %s\n", mysql_error(conn));
    }

    mysql_library_end();  // Cleanup (optional)

    return 0;
}

Selecting and Printing Data from a Table:

#include <mysql.h>

int main() {
    MYSQL *conn;

    // Initialize the connector
    mysql_library_init(NULL, NULL);

    // Connection details (replace with your actual values)
    const char *server = "localhost";
    const char *user = "your_username";
    const char *password = "your_password";
    const char *database = "your_database";

    // Connect to the MariaDB server
    conn = mysql_real_connect(conn, server, user, password, database, 0, NULL, 0);

    if (conn) {
        printf("Connected to MariaDB server\n");

        // Select data from a table
        const char *select_query = "SELECT * FROM users";
        MYSQL_RES *result = mysql_query(conn, select_query);

        if (result) {
            int num_fields = mysql_num_fields(result



  • If you prefer a more modern and potentially easier-to-use language for interacting with MariaDB, consider options like:
    • C++: The MariaDB Connector/C++ offers an object-oriented API for C++ applications, simplifying database interaction.
    • Python: Libraries like mysqlclient provide a convenient way to connect and manipulate data in MariaDB from Python programs.
    • Java: The MariaDB JDBC Driver enables Java applications to access MariaDB databases.

Using Object-Relational Mappers (ORMs):

  • ORMs like Hibernate (Java) or SQLAlchemy (Python) can streamline database interactions by providing an abstraction layer. They handle the underlying SQL details and mapping between database objects and application classes, reducing the need for raw SQL queries in your C code.

Embedded MariaDB:

  • If you need a lightweight database solution embedded within your C application, consider using the embedded MariaDB library. This option allows you to directly embed a MariaDB server into your program, providing database functionality without requiring a separate server process.

Choosing the Right Approach:

The best approach depends on your project's specific requirements. Here are some factors to consider:

  • Project Language: If you're already comfortable with C and prefer a lower-level approach, the MariaDB Connector/C remains a viable option.
  • Developer Experience: For a more developer-friendly experience, consider using C++ with the MariaDB Connector/C++ or a higher-level language like Python with its database libraries.
  • Project Complexity: For simpler database interactions, using a higher-level language with an ORM might be easier to manage.
  • Project Scope: If you need an embedded database solution within your C application, the embedded MariaDB library might be a suitable choice.

c mariadb



Fixing 'MariaDB Engine Won't Start' Error on Windows

MariaDB: An open-source relational database management system similar to MySQL.Windows: The operating system where MariaDB is installed...


Understanding "Grant All Privileges on Database" in MySQL/MariaDB

In simple terms, "granting all privileges on a database" in MySQL or MariaDB means giving a user full control over that specific database...


MAMP with MariaDB: Configuration Options

Stands for Macintosh Apache MySQL PHP.It's a local development environment that bundles Apache web server, MySQL database server...


MySQL 5 vs 6 vs MariaDB: Choosing the Right Database Server

The original open-source relational database management system (RDBMS).Widely used and considered the industry standard...


Beyond Backups: Alternative Approaches to MySQL to MariaDB Migration

There are two main approaches depending on your comfort level:Complete Uninstall/Install:Stop the MySQL server. Uninstall MySQL...



c mariadb

Troubleshooting MySQL Error 1153: Got a packet bigger than 'max_allowed_packet' bytes

MySQL Error 1153: This specific error code indicates that the database server (MySQL or MariaDB) has rejected a data packet sent by the client (mysql or another tool) because the packet size exceeds the server's configured maximum allowed packet size


SQLite INSERT Performance: A Guide to Faster Data Insertion

SQLite is a lightweight, embedded database engine that excels in many use cases, including mobile applications. However


Speed Up Your Inserts: Multi-Row INSERT vs. Multiple Single INSERTs in MySQL/MariaDB

Reduced Overhead: Sending a single INSERT statement with multiple rows requires less network traffic compared to sending many individual INSERT statements


Understanding MySQL's SELECT * INTO OUTFILE LOCAL Statement

Functionality:This statement exports the results of a MySQL query to a plain text file on the server that's running the MySQL database


MariaDB for Commercial Use: Understanding Licensing and Support Options

Commercial License: Typically refers to a license where you pay a fee to use software for commercial purposes (selling a product that uses the software)