How to connect to MySQL using C++

How to connect to MySQL using C++

C++ connects to MySQL for your reference. The specific contents are as follows

Defining the MySQLCon Class

class MySQLCon
{
 MYSQLmysql;
public:
 int errornum;
 string errortext;
public:
 //Initialize MySQLCon();
 //Close the database~MySQLCon();
 //Connect to database bool OpenConn(const char* host,const char* username,const char* pwd,const char* dbName,unsigned port=0);
 void GetErrorText();//Get error text void Close();//Close database bool ExecuteSQL(const char* sql);//Use SQL statement, unable to receive data bool QureySQL(const char* sql, vector<vector<string>>& resultSet);//Use SQL statement and receive data (select statement)
};

Initialization Operation

MySQLCon::MySQLCon()
{
 if (mysql_library_init(0, nullptr, nullptr)) 
 {
 cout << "CAPI initialization failed" << std::endl;
 getchar();
 exit(1);
 }
 if (mysql_init(&mysql)==nullptr)
 {
 cout << "Failed to initialize database variables" << std::endl;
 getchar();
 exit(1);
 }
 if (mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "gbk"))
 {
 cout << "Failed to set connection options" << std::endl;
 getchar();
 exit(1);
 }
}

Connecting to MySQL Server

//The parameters are host, username, password, database name, port number bool MySQLCon::OpenConn(const char* host, const char* username, const char* pwd, const char* dbName, unsigned port)
{
 //Connect to the database if (mysql_real_connect(&mysql, host, username, pwd, dbName, port, nullptr, 0)==nullptr)
 {
 cout << "Failed to connect to MySQL server" << std::endl;
 //Get the error text GetErrorText();
 exit(1);
 return false;
 }
 return true;
 
}

Get MySQL error information

void MySQLCon::GetErrorText()
{
 //Get the error code errornum = mysql_errno(&mysql);
 //Get the error text errortext = mysql_error(&mysql);
 //Print error code cout << "error num: " << errornum << std::endl;
 //Print error text cout << "error text: " << errortext << std::endl;
 getchar();
}

Using SQL statements in C++

bool MySQLCon::ExecuteSQL(const char* sql)
{
 //Use SQL statement but cannot receive data if (mysql_real_query(&mysql, sql, strlen(sql)))
 {
 GetErrorText();
 return false;
 }
 return true;
}
bool MySQLCon::QureySQL(const char* sql, vector<vector<string>>& resultSet)
{
 //Use SQL statements and receive data into vector container if (mysql_real_query(&mysql, sql, strlen(sql)))
 {
 GetErrorText();
 return false;
 }
 //Create a MYSQL result set MYSQL_RES* result = mysql_store_result(&mysql);
 //Get the total number of rows and columns unsigned int rows = mysql_num_rows(result);
 unsigned int cols = mysql_num_fields(result);
 //Used to record a piece of data in the result set MYSQL_ROW row;
 while (row = mysql_fetch_row(result))
 {
 //Create a vector container to store the data in row vector<string> lineDate;
 for (int i = 0; i < cols; i++)
 {
 if (row[i])
 {
 //Store the data of each column in row into lineDate lineDate.push_back(row[i]);
 }
 else
 {
 lineDate.push_back("");
 }
 }
 //Store the entire line of data in resultSet resultSet.push_back(lineDate);
 }
 //Release the result setmysql_free_result(result);
 return true;
}

Close the database

void MySQLCon::Close()
{
 mysql_close(&mysql);
}
MySQLCon::~MySQLCon()
{
 Close();
 mysql_library_end();
}

Example main function

int main()
{
 MySQLCon c_apiconn;
 c_apiconn.OpenConn("127.0.0.1", "root", "136119", "fancy");
 string sql = "use fancy;"
 vector<vector<string>> data;
 c_apiconn.ExecuteSQL(sql.c_str());
 sql = "select * from fancy.info;";
 c_apiconn.QureySQL(sql.c_str(), data);
 for (int i = 0; i < data.size(); i++)
 {
 for (int j = 0; j < data[i].size(); j++)
 {
 cout << data[i][j] << "\t";
 }
 cout << endl;
 }
 return 0;
}

Output

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Summary of two methods of connecting to MySQL database in C++
  • Connecting to MySQL database in C++ in Eclipse
  • Solution to LNK2019 error when C++ uses MySQL-Connector/C++ to connect to MySQL
  • C/C++ method to connect to MySql database
  • How to connect to MySQL in C++ (directly call C-API)
  • Detailed explanation of using MySQL API to connect and operate database examples in C++
  • Summary of errors in connecting C++ to MySQL 5.6
  • Summary of problems encountered when connecting C++ to MySQL
  • C++ uses mysql's own header file to connect to the database
  • Two ways to connect to MySQL database in C++ (ADO connection and MySQL API connection)

<<:  How to configure port forwarding for docker on CentOS 7 to be compatible with firewall

>>:  22 Vue optimization tips (project practical)

Recommend

About Tomcat combined with Atomikos to implement JTA

Recently, the project switched the environment an...

More popular and creative dark background web design examples

Dark background style page design is very popular...

Sample code for generating QR code using js

Some time ago, the project needed to develop the ...

Example of how to set up a multi-column equal height layout with CSS

Initially, multiple columns have different conten...

MySQL database query performance optimization strategy

Optimize queries Use the Explain statement to ana...

Users need to know why

When I was in the securities company, because the ...

Implementation of waterfall layout in uni-app project

GitHub address, you can star it if you like it Pl...

Design a data collector with vue

Table of contents Scenario Core Issues Status mon...

About the selection of time date type and string type in MySQL

Table of contents 1. Usage of DATETIME and TIMEST...

Detailed explanation of several ways to install CMake on Ubuntu

apt install CMake sudo apt install cmake This met...

JavaScript to achieve digital clock effect

This article example shares the specific code of ...

How to use squid to build a proxy server for http and https

When we introduced nginx, we also used nginx to s...

Explore JavaScript prototype data sharing and method sharing implementation

Data Sharing What kind of data needs to be writte...

Use of LRU algorithm in Vue built-in component keep-alive

Table of contents The use of Vue's keep-alive...