Updating Data in MySQL Using C++

A guide on how to update data in MySQL using C++ with Prepared Statements, ensuring security and efficiency when interacting with the database. This article provides a clear illustrative example.

In this article, we will explore how to update data in MySQL using the C++ programming language. By using Prepared Statements, we can protect the data from SQL Injection attacks and improve performance when processing multiple records.

C++ Code

#include <mysql/mysql.h>
#include <iostream>

int main() {
    // Initialize MySQL
    MYSQL* conn = mysql_init(NULL);

    // Connect to the database
    if (conn == NULL) {
        std::cerr << "Unable to initialize MySQL connection\n";
        return EXIT_FAILURE;
    }

    if (mysql_real_connect(conn, "localhost", "username", "password", "database_name", 0, NULL, 0) == NULL) {
        std::cerr << "MySQL connection error: " << mysql_error(conn) << "\n";
        mysql_close(conn);
        return EXIT_FAILURE;
    }

    // Prepare the UPDATE statement
    const char* query = "UPDATE students SET name = ? WHERE id = ?";
    MYSQL_STMT* stmt = mysql_stmt_init(conn);

    if (!stmt) {
        std::cerr << "Unable to initialize Prepared Statement\n";
        mysql_close(conn);
        return EXIT_FAILURE;
    }

    if (mysql_stmt_prepare(stmt, query, strlen(query))) {
        std::cerr << "Statement preparation error: " << mysql_stmt_error(stmt) << "\n";
        mysql_stmt_close(stmt);
        mysql_close(conn);
        return EXIT_FAILURE;
    }

    // Set the parameters
    MYSQL_BIND bind[2];
    memset(bind, 0, sizeof(bind));

    std::string name = "Nguyen Van A";
    int id = 1;

    bind[0].buffer_type = MYSQL_TYPE_STRING;
    bind[0].buffer = (char*)name.c_str();
    bind[0].buffer_length = name.length();

    bind[1].buffer_type = MYSQL_TYPE_LONG;
    bind[1].buffer = (char*)&id;
    bind[1].is_null = 0;

    if (mysql_stmt_bind_param(stmt, bind)) {
        std::cerr << "Parameter binding error: " << mysql_stmt_error(stmt) << "\n";
        mysql_stmt_close(stmt);
        mysql_close(conn);
        return EXIT_FAILURE;
    }

    // Execute the statement
    if (mysql_stmt_execute(stmt)) {
        std::cerr << "Execution error: " << mysql_stmt_error(stmt) << "\n";
        mysql_stmt_close(stmt);
        mysql_close(conn);
        return EXIT_FAILURE;
    }

    std::cout << "Data updated successfully!\n";

    // Close the connection
    mysql_stmt_close(stmt);
    mysql_close(conn);

    return EXIT_SUCCESS;
}

Detailed explanation

  • mysql_init: Initializes a MySQL object.
  • mysql_real_connect: Connects to the MySQL database.
  • mysql_stmt_init: Creates a Prepared Statement object.
  • mysql_stmt_prepare: Prepares the SQL statement with unknown parameters.
  • mysql_stmt_bind_param: Binds the parameters to the statement.
  • mysql_stmt_execute: Executes the SQL statement.
  • mysql_stmt_close and mysql_close: Closes the Prepared Statement and MySQL connection.

System Requirements:

  • C++ Compiler (g++ or Visual Studio)
  • MySQL Connector/C++ (MySQL C API)
  • MySQL server

How to install the libraries needed to run the C++ code above:

  1. Install MySQL Connector/C++.
  2. Include the mysql.h header file and link with libmysqlclient when compiling.

Tips:

  • Ensure you've configured the correct username, password, and database name.
  • Use Prepared Statements to avoid SQL Injection attacks and improve performance.
Tags: MySQL, C++


Related

Multithreading in C++

A detailed guide on handling multithreading in C++ using the `thread` library. This article helps you understand how to use multithreading to improve concurrent processing efficiency.
All Methods for String Concatenation in C++

This article compiles all methods for string concatenation in C++, helping you understand the different methods from basic to advanced, including using the `+` operator, the `append()` function, and methods from the `string` library.
Create a Simple Chat Application Using Socket.IO in C++

A guide on how to create a simple chat application using C++ with Socket.IO, helping you to understand more about network programming and real-time communication.
Common Functions When Using Selenium Chrome in C++

This article lists the common functions used when working with Selenium Chrome in C++, helping readers quickly grasp the necessary operations for browser automation.
Updating Multiple Columns in MySQL Using C++

A detailed guide on updating multiple columns in MySQL using C++ with Prepared Statements. This article helps you understand how to use Prepared Statements to update data securely and efficiently.
How to append an Authentication Header Token when POSTing data to an API in C++

A guide on how to pass an authentication token via the Authentication Header when POSTing data to an API using C++. The example utilizes the `libcurl` library to perform HTTP requests with token-based authentication.
Create a Thumbnail for Images in C++

A detailed guide on how to create a thumbnail for images in C++ using the OpenCV library. This article will help you understand how to process images and easily resize them to create thumbnails.
Reading Excel File Content in C++

A detailed guide on reading the content of an Excel file in C++ using the `xlnt` library. This article will help you understand how to retrieve data from an Excel file and process it in your C++ program.
Using Selenium in C++ to send JavaScript code to a website on Chrome

A guide on using Selenium in C++ to send JavaScript code to a website via the Chrome browser. This article will instruct you on setup and coding for this task.
Fetching Data from MySQL Database in C++

A detailed guide on how to fetch data from a MySQL database using C++ with Prepared Statements. The article helps you understand how to connect, execute queries, and handle results using MySQL Connector/C++.

main.add_cart_success