search
HomeDatabaseMysql TutorialHow to connect to mysql database and read data in 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>

    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
    						)

    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)

    Or:

    int
    mysql_real_query(MYSQL *mysql,
                     const char *stmt_str,
                     unsigned long length)
    • 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)

    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)

    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;
     
    }

    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
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

    In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

    How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

    To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

    MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

    MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

    Describe MySQL asynchronous master-slave replication process.Describe MySQL asynchronous master-slave replication process.Apr 10, 2025 am 09:30 AM

    MySQL asynchronous master-slave replication enables data synchronization through binlog, improving read performance and high availability. 1) The master server record changes to binlog; 2) The slave server reads binlog through I/O threads; 3) The server SQL thread applies binlog to synchronize data.

    MySQL: Simple Concepts for Easy LearningMySQL: Simple Concepts for Easy LearningApr 10, 2025 am 09:29 AM

    MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

    MySQL: A User-Friendly Introduction to DatabasesMySQL: A User-Friendly Introduction to DatabasesApr 10, 2025 am 09:27 AM

    The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

    How does the InnoDB Buffer Pool work and why is it crucial for performance?How does the InnoDB Buffer Pool work and why is it crucial for performance?Apr 09, 2025 am 12:12 AM

    InnoDBBufferPool improves the performance of MySQL databases by loading data and index pages into memory. 1) The data page is loaded into the BufferPool to reduce disk I/O. 2) Dirty pages are marked and refreshed to disk regularly. 3) LRU algorithm management data page elimination. 4) The read-out mechanism loads the possible data pages in advance.

    MySQL: The Ease of Data Management for BeginnersMySQL: The Ease of Data Management for BeginnersApr 09, 2025 am 12:07 AM

    MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

    See all articles

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool