Table of Contents
1. The header file of mysql API needs to be included
2. Specific steps to connect to mysql
2.1 mysql_real_connect
2.2 mysql_query or mysql_real_query
2.3 Get the result set mysql_store_result
2.4 Display each row of data in the result set
3. A programming example
Home Database Mysql Tutorial How to connect to mysql database and read data in C++

How to connect to mysql database and read data in C++

Jun 03, 2023 am 09:05 AM
mysql c++

    1. The header file of mysql API needs to be included

    If you need to connect to the local mysql database, the premise is that the mysql database must have been installed locally. Some mysql APIs are used here, such as connecting to the database, executing query statements and other operations. These interfaces are included in the following header files:

    #include <mysql/mysql.h>
    Copy after login

    2. Specific steps to connect to mysql

    Here It can be roughly divided into four main steps:

    1. Connect to mysql database

    1. Connect to mysql database

    Obviously, if you want to obtain the data in mysql data, you must first connect Database, obtain a handle that can operate the database.

    2. Execute the query statement, that is, select the data we need.

    is to execute the query statement and query the data we need. The queried data will be saved in a place called the result set.

    3. Obtain the required data from the result set

    Use the relevant interface functions to obtain the data of each row and local field from the result set.

    4. Extract the information of each field in each row from the result set

    5. Release resources, including the result set mysql handle

    The following will explain in detail a few that must be used Key interface functions.

    2.1 mysql_real_connect

    This function is used to connect to the database engine running on the host. If the connection is successful, a handle that can operate the database will be obtained, otherwise a NULL pointer will be returned.

    MYSQL *mysql_real_connect(MYSQL *mysql, 
    						const char *host, 
    						const char *user, 
    						const char *passwd, 
    						const char *db, 
    						unsigned int port, 
    						const char *unix_socket, 
    						unsigned long client_flag
    						)
    Copy after login

    This function has many parameters, and the meaning of each parameter is as follows:

    • mysql: It is the address of the existing MYSQL structure. Before calling mysql_real_connect(), mysql_init() must be called to initialize the MYSQL structure.

    • #host: is the host name or IP address. If "host" is NULL or the string "localhost", the connection will be treated as a connection to localhost.

    • #user: The user’s MySQL login ID. If "user" is NULL or the empty string "", the user will be considered the current user.

    • passwd: User’s password. If "passwd" is NULL, only entries in the user's user table (that have an empty password field) will be checked for a match.

    • db: is the database name. If db is NULL, the connection will set the default database to this value.

    • port: If "port" is not 0, its value will be used as the port number for the TCP/IP connection. Note that the "host" parameter determines the type of connection.

    • unix_socket: If unix_socket is not NULL, this string describes the socket or named pipe that should be used. Note that the "host" parameter determines the type of connection.

    • client_flag: The value is usually 0

    2.2 mysql_query or mysql_real_query

    This function is used Send a query command to the database and let the database execute it. Returning 0 indicates that the query is successful, otherwise it fails.

    int mysql_query(MYSQL *mysql, const char *stmt_str)
    Copy after login

    Or:

    int
    mysql_real_query(MYSQL *mysql,
                     const char *stmt_str,
                     unsigned long length)
    Copy after login
    • mysql: is the mysql operation handle obtained through.

    • stmt_str: Indicates the query statement that needs to be executed.

    • #length: is the length of the query statement.

    The difference between the above two functions is:

    • mysql_query() cannot be used to execute binary statements, that is, the parameter stmt_str cannot There is binary data, which will be parsed into characters.

    • mysql_query query speed is slightly slower because the length of the query statement needs to be calculated

    2.3 Get the result set mysql_store_result

    The The function returns the result set if the query is successful. If it fails, it returns NULL

    MYSQL_RES *mysql_store_result(MYSQL *mysql)
    Copy after login

    2.4 Display each row of data in the result set

    The input parameter of this function is the result set returned in step (3). Each time it is called, the next row of data in the result set is returned and the pointer is moved backward by one row. If there is no next row of data, NULL is returned.
    You can use mysql_num_fields(result) to calculate the number of rows in the result set, and mysql_num_fields(result) to calculate the number of columns. If row is the information of a certain row, then row[0], row[1]. . . Each field information of the row.

    MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
    Copy after login

    3. A programming example

    The environment here is a linux system. The local database name used is: CrashCourse, and the query table name is products. The following programming example demonstrates querying all items with a price greater than 30 in the products table. The complete content of the products table is as follows:

    How to connect to mysql database and read data in C++

    #include 
    #include <mysql/mysql.h>
    #include 
    using namespace std;
     
    MYSQL mysql;  //mysql连接
    MYSQL_RES* res; //结果集结构体   
    MYSQL_ROW row; //char** 二维数组,存放记录  
     
    int main()
    {	
    	// 步骤1: 初始化并连接数据库,获得操作数据库的句柄
    	mysql_init(&mysql);    //初始化
    	if (!(mysql_real_connect(&mysql, "localhost", "root", "root", "CrashCourse", 0, NULL, 0))) {
    		cout << "Couldn't connect to Database!\n : " << mysql_error(&mysql);
    		exit(1);
    	}
    	else {
    		printf("Database connection succeeded. Connected...\n\n");
    	}
    	// 步骤2: 执行查询语句,查询需要的数据(设置编码格式也相当于执行特殊的查询语句)
    	mysql_query(&mysql, "set names gbk"); // 设置编码格式
    	mysql_query(&mysql, "SELECT * from products where prod_price > 30");
     
    	// 步骤3:获取结果集
    	res = mysql_store_result(&mysql);
    	// 步骤4:显示结果集中每行数据
        int cols = mysql_num_fields(res); // 计算结果集中,列的个数
    	while (row = mysql_fetch_row(res)) {
        
        	for (int i = 0; i < cols; ++i) {
          		cout << row[i] << "\t";
        	}
        	cout << endl;
    	}
     	// 步骤5:释放结果集合mysql句柄
    	mysql_free_result(res);
    	mysql_close(&mysql);
     return 0;
     
    }
    Copy after login

    The query results are as follows:

    How to connect to mysql database and read data in C++

    The above is the detailed content of How to connect to mysql database and read data in C++. For more information, please follow other related articles on the PHP Chinese website!

    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

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

    The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

    The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

    Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

    How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

    In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

    Do you use c in visual studio code Do you use c in visual studio code Apr 15, 2025 pm 08:03 PM

    Writing C in VS Code is not only feasible, but also efficient and elegant. The key is to install the excellent C/C extension, which provides functions such as code completion, syntax highlighting, and debugging. VS Code's debugging capabilities help you quickly locate bugs, while printf output is an old-fashioned but effective debugging method. In addition, when dynamic memory allocation, the return value should be checked and memory freed to prevent memory leaks, and debugging these issues is convenient in VS Code. Although VS Code cannot directly help with performance optimization, it provides a good development environment for easy analysis of code performance. Good programming habits, readability and maintainability are also crucial. Anyway, VS Code is

    MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

    The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

    How to call docker lnmp How to call docker lnmp Apr 15, 2025 am 11:15 AM

    Docker LNMP container call steps: Run the container: docker run -d --name lnmp-container -p 80:80 -p 443:443 lnmp-stack to get the container IP: docker inspect lnmp-container | grep IPAddress access website: http://&lt;Container IP&gt;/index.phpSSH access: docker exec -it lnmp-container bash access MySQL: mysql -u roo

    What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

    VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

    Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

    The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

    See all articles