How to connect to mysql database and read data in C++
Jun 03, 2023 am 09:05 AM1. 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:
#include#include <mysql/mysql.h> #include using namespace std; MYSQL mysql; //mysql連接 MYSQL_RES* res; //結(jié)果集結(jié)構(gòu)體 MYSQL_ROW row; //char** 二維數(shù)組,存放記錄 int main() { // 步驟1: 初始化并連接數(shù)據(jù)庫(kù),獲得操作數(shù)據(jù)庫(kù)的句柄 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: 執(zhí)行查詢語(yǔ)句,查詢需要的數(shù)據(jù)(設(shè)置編碼格式也相當(dāng)于執(zhí)行特殊的查詢語(yǔ)句) mysql_query(&mysql, "set names gbk"); // 設(shè)置編碼格式 mysql_query(&mysql, "SELECT * from products where prod_price > 30"); // 步驟3:獲取結(jié)果集 res = mysql_store_result(&mysql); // 步驟4:顯示結(jié)果集中每行數(shù)據(jù) int cols = mysql_num_fields(res); // 計(jì)算結(jié)果集中,列的個(gè)數(shù) while (row = mysql_fetch_row(res)) { for (int i = 0; i < cols; ++i) { cout << row[i] << "\t"; } cout << endl; } // 步驟5:釋放結(jié)果集合mysql句柄 mysql_free_result(res); mysql_close(&mysql); return 0; }
The query results are as follows:
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In C, the POD (PlainOldData) type refers to a type with a simple structure and compatible with C language data processing. It needs to meet two conditions: it has ordinary copy semantics, which can be copied by memcpy; it has a standard layout and the memory structure is predictable. Specific requirements include: all non-static members are public, no user-defined constructors or destructors, no virtual functions or base classes, and all non-static members themselves are PODs. For example structPoint{intx;inty;} is POD. Its uses include binary I/O, C interoperability, performance optimization, etc. You can check whether the type is POD through std::is_pod, but it is recommended to use std::is_trivia after C 11.

MySQL query performance optimization needs to start from the core points, including rational use of indexes, optimization of SQL statements, table structure design and partitioning strategies, and utilization of cache and monitoring tools. 1. Use indexes reasonably: Create indexes on commonly used query fields, avoid full table scanning, pay attention to the combined index order, do not add indexes in low selective fields, and avoid redundant indexes. 2. Optimize SQL queries: Avoid SELECT*, do not use functions in WHERE, reduce subquery nesting, and optimize paging query methods. 3. Table structure design and partitioning: select paradigm or anti-paradigm according to read and write scenarios, select appropriate field types, clean data regularly, and consider horizontal tables to divide tables or partition by time. 4. Utilize cache and monitoring: Use Redis cache to reduce database pressure and enable slow query

In C, there are three main ways to pass functions as parameters: using function pointers, std::function and Lambda expressions, and template generics. 1. Function pointers are the most basic method, suitable for simple scenarios or C interface compatible, but poor readability; 2. Std::function combined with Lambda expressions is a recommended method in modern C, supporting a variety of callable objects and being type-safe; 3. Template generic methods are the most flexible, suitable for library code or general logic, but may increase the compilation time and code volume. Lambdas that capture the context must be passed through std::function or template and cannot be converted directly into function pointers.

CTEs are a feature introduced by MySQL8.0 to improve the readability and maintenance of complex queries. 1. CTE is a temporary result set, which is only valid in the current query, has a clear structure, and supports duplicate references; 2. Compared with subqueries, CTE is more readable, reusable and supports recursion; 3. Recursive CTE can process hierarchical data, such as organizational structure, which needs to include initial query and recursion parts; 4. Use suggestions include avoiding abuse, naming specifications, paying attention to performance and debugging methods.

MySQL's EXPLAIN is a tool used to analyze query execution plans. You can view the execution process by adding EXPLAIN before the SELECT query. 1. The main fields include id, select_type, table, type, key, Extra, etc.; 2. Efficient query needs to pay attention to type (such as const, eq_ref is the best), key (whether to use the appropriate index) and Extra (avoid Usingfilesort and Usingtemporary); 3. Common optimization suggestions: avoid using functions or blurring the leading wildcards for fields, ensure the consistent field types, reasonably set the connection field index, optimize sorting and grouping operations to improve performance and reduce capital

The aggregation function is used to perform calculations on a set of values ??and return a single value. Common ones include COUNT, SUM, AVG, MAX, and MIN; GROUPBY groups data by one or more columns and applies an aggregation function to each group. For example, GROUPBYuser_id is required to count the total order amount of each user; SELECTuser_id, SUM(amount)FROMordersGROUPBYuser_id; non-aggregated fields must appear in GROUPBY; multiple fields can be used for multi-condition grouping; HAVING is used instead of WHERE after grouping; application scenarios such as counting the number of classified products, maximum ordering users, monthly sales trends, etc. Mastering these can effectively solve the number

The key to an abstract class is that it contains at least one pure virtual function. When a pure virtual function is declared in the class (such as virtualvoiddoSomething()=0;), the class becomes an abstract class and cannot directly instantiate the object, but polymorphism can be realized through pointers or references; if the derived class does not implement all pure virtual functions, it will also remain an abstract class. Abstract classes are often used to define interfaces or shared behaviors, such as designing Shape classes in drawing applications and implementing the draw() method by derived classes such as Circle and Rectangle. Scenarios using abstract classes include: designing base classes that should not be instantiated directly, forcing multiple related classes to follow a unified interface, providing default behavior, and requiring subclasses to supplement details. In addition, C

In C, the mutable keyword is used to allow the object to be modified, even if the object is declared as const. Its core purpose is to maintain the logical constants of the object while allowing internal state changes, which are commonly found in cache, debug counters and thread synchronization primitives. When using it, mutable must be placed before the data member in the class definition, and it only applies to data members rather than global or local variables. In best practice, abuse should be avoided, concurrent synchronization should be paid attention to, and external behavior should be ensured. For example, std::shared_ptr uses mutable to manage reference counting to achieve thread safety and const correctness.
