Direct operation of MySQL, inefficient input commands, MySQL embedded in the program, encapsulate the interface, let the program to access MySQL, in order to maximize the efficiency of using MySQL.
MySQL C API migration
The project files containing MySQL should not be directly related to the installed MySQL of the computer, because different computer servers are installed in different locations and each migration requires a redeployment of the installation environment. MySQL header files and operating library files should be copied to engineering files, so that even if transplanted to other MySQL computers or servers installed, there is no need to relocate header files and related library files, and access the database directly. Unless the interface parameters change with the upgrade of MySQL version, they can be used directly.
After transplantation, even if the device is not equipped with MySQL, the code can be compiled, but it can not run without MySQL, and the project can not be compiled and passed because the device is not equipped with MySQL.
Porting MySQL header files
The Makefile project built in linux needs to install libmysqlclient-dev to use API interface header files.
Command: sudo apt-get install libmysqlclient-dev
After installation, the header file is in: / usr/include/mysql
ghost@ghost-machine:/usr/include$ ls mysql/
big_endian.h my_global.h plugin_audit.h
binary_log_types.h my_list.h plugin_auth_common.h
byte_order_generic.h mysql plugin_ftparser.h
byte_order_generic_x86.h mysql_com.h plugin_group_replication.h
decimal.h mysql_com_server.h plugin.h
errmsg.h mysqld_ername.h plugin_keyring.h
keycache.h mysqld_error.h plugin_validate_password.h
little_endian.h mysql_embed.h psi
m_ctype.h mysql.h sql_common.h
m_string.h mysql_time.h sql_state.h
my_alloc.h mysql_version.h sslopt-case.h
my_byteorder.h mysqlx_ername.h sslopt-longopts.h
my_command.h mysqlx_error.h sslopt-vars.h
my_compiler.h mysqlx_version.h thr_cond.h
my_config.h my_sys.h thr_mutex.h
my_dbug.h my_thread.h thr_rwlock.h
my_dir.h my_thread_local.h typelib.h
my_getopt.h my_xml.h
Windows MySQL header file is in the installation directory.
MySQL header file: C: Program Files MySQL MySQL Server 5.7 include include C++ operation header file: C: Program Files MySQL Connector. C++ 1.1
The header file structure of windows and Linux is slightly different, but they are basically the same. This migration is the MySQL header file of linux.
It is not recommended to use C++ to manipulate header files, because boost libraries are needed, and the installation and compilation of boost libraries are cumbersome.
Copy all header files to the project header file.
Command: test_makefile/inc$cp/usr/include/mysql/. / -rf
The directory of the replicated project header file is shown in the following figure
Makefile Project:
Add the header file to Makefile and edit Makefile.
NC += -I$(DIR)/inc/mysql
Visual Studio Project
The reference header file is shown in the following figure
Porting MySQL Library Files
Makefile Project
Because the library files ported by Makefile project are. so or. a, it is necessary to transplant MySQL library files under Linux.
Like header files, linux needs to install libmysqlclient-dev to use API interface header files.
Order:
sudo apt-get install libmysqlclient-dev
After installation, the library files are under: / usr/lib/mysql and / usr/lib
Visual Studio Project
Unlike Linux, the library files ported by Visual Studio project are. lib or. dll.
Library file location:
C:\Program Files\MySQL\MySQL Server 5.7\lib
File location is MySQL installation location.
As shown in the following figure
Copy all library files to the directory of engineering library files
├── open_lib
│ ├── MySQL_lib
│ │ ├── libmysql.dll
│ │ ├── libmysql.lib
│ │ └── mysqlclient.lib
The project references library files, as shown in the following figure
Add the project running environment dll. In order to ensure that the program does not depend on the system environment variables after running, it is necessary to put DLL in the output folder of the compiler. If obj is defined as the output folder, DLL is put in the folder. As shown in the figure below.
Add MySQL sample
Project adds MySQL sample to test MySQL migration project.
module_MySQL.cpp
#include "module_MySQL.h"
#include <iostream>
#include <string>
#include <mysql/mysql.h>
using namespace std;
void TestMySQL(void)
{
cout << __FUNCTION__ << " is called." << endl;
MYSQL mysql;
mysql_init(&mysql);
mysql_real_connect(&mysql, "localhost", "zxpro-admin", "qwerty", "zx_mysql", 3306, NULL, 0);
//MySQL command
string sql = "select * from zx_users;";
mysql_query(&mysql, sql.c_str());
try
{
MYSQL_RES *result = mysql_store_result(&mysql);
if (!result)
throw string("MySQL not result!");
//Get the number of fields
int num_fields = mysql_num_fields(result);
if(0 == num_fields)
throw string("MySQL fields number is 0!");
//Get the field name
MYSQL_FIELD *fields = mysql_fetch_fields(result);
if (!fields)
throw string("MySQL fields fetch is error!");
for (int i = 0; i < num_fields; i++)
{
cout << "field " << i << " name is " << fields[i].name << endl;
}
cout << "MySQL is OK." << endl;
}
catch (string &error_msg)
{
cout << error_msg << endl;
}
catch (...)
{
cout << "MySQL operation is error!" << endl;
}
mysql_close(&mysql);
}
The database structure is shown in the figure below.
The results of the example project are shown in the following figure.
MySQL C API
Official documents: https://dev.mysql.com/doc/refman/5.7/en/c-api.html
Header file contains
To use MySQL's interface API, you need to include header files
#include <mysql/mysql.h>
Log in to MySQL: mysql_init(), mysql_real_connect()
Function prototype:
MYSQL * STDCALL mysql_init(MYSQL *mysql);
//Successfully returns the * mysql pointer and fails to return NULL.
MYSQL * STDCALL mysql_real_connect(MYSQL *mysql,
const char *host, //MySQL IP, remote login input IP address of remote login
const char *user, //log on user
const char *passwd, //Login password
const char *db, //The name of the database used
unsigned int port, //MySQL port
const char *unix_socket, //Whether to log in using socket mechanism, NULL: No
unsigned long clientflag); //Connection flag, usually 0
//Successfully returns the * mysql pointer and fails to return NULL.
clientflag connection flag is defined in the file: mysql_com.h with # define CLIENT_*
The following intercepted fragments:
#define CLIENT_LONG_PASSWORD 1 /* new more secure passwords */
#define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */
#define CLIENT_LONG_FLAG 4 /* Get all column flags */
#define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */
#define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */
#define CLIENT_COMPRESS 32 /* Can use compression protocol */
#define CLIENT_ODBC 64 /* Odbc client */
#define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */
#define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */
#define CLIENT_PROTOCOL_41 512 /* New 4.1 protocol */
#define CLIENT_INTERACTIVE 1024 /* This is an interactive client */
#define CLIENT_SSL 2048 /* Switch to SSL after handshake */
#define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */
#define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */
#define CLIENT_RESERVED 16384 /* Old flag for 4.1 protocol */
#define CLIENT_RESERVED2 32768 /* Old flag for 4.1 authentication */
Example: Log on to MySQL database
try
{
if (!mysql_init(&mysql))
throw string("MySQL init is error!");
if (!mysql_real_connect(&mysql, "localhost", "zxpro-admin", "qwerty", "zx_mysql", 3306, NULL, 0))
throw string("MySQL connect is error!");
catch (string &error_msg)
{
cout << error_msg << endl;
}
catch (...)
{
cout << "MySQL operation is error!" << endl;
}
mysql_close(&mysql);
Operate MySQL: mysql_query()
Function prototype:
int STDCALL mysql_query(MYSQL *mysql, //MySQL Operational Architecture
const char *q); //Operation command
//Successful return 0, Failure Return 1
Call mysql_error() when failure occurs and return a description of the specific failure
Example: Operating MySQL database
try
{
…………………
string sql = "SELECT * from zx_users;";
if (mysql_query(&mysql, sql.c_str()))
{
string err_string = mysql_error(&mysql);
if(err_string.empty())
throw string("MySQL query is error!");
else
throw err_string;
}
………………
}
catch (string &error_msg)
{
cout << error_msg << endl;
}
catch (...)
{
cout << "MySQL operation is error!" << endl;
}
mysql_close(&mysql);
The printing of command errors is shown in the following figure:
Close MySQL: mysql_close()
Function prototype:
void STDCALL mysql_close(MYSQL *sock);
Example: Close MySQL database
mysql_close(&mysql);
Read MySQL data: mysql_store_result()
Get the command result function: mysql_store_result()
Read field function: mysql_fetch_fields()
Read field number function: mysql_num_fields()
Read data function: mysql_fetch_row()
Release result function: mysql_free_result(result);
Function prototype
MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql);
unsigned int STDCALL mysql_num_fields(MYSQL_RES *res);
MYSQL_FIELD * STDCALL mysql_fetch_fields(MYSQL_RES *res);
typedef char **MYSQL_ROW; /* return data as array of strings */
MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result);
void STDCALL mysql_free_result(MYSQL_RES *result);
mysql_fetch_fields returns field types, including field names, field length, and other field properties.
MYSQL_FIELD Structural Definition: mysql.h
typedef struct st_mysql_field {
char *name; /* Name of column */
………………………….
} MYSQL_FIELD;
Read specific data focus:
mysql_fetch_row returns a char-type double pointer pointing to an array of corresponding fields. The data in the array is shown in string form. If the field is empty, the content is NULL. After reading a set of fields, the call points to the next field and returns to NULL.
Test program
try
{
………………………………….
//MySQL command
string sql = "SELECT * from zx_users;";
if (mysql_query(&mysql, sql.c_str()))
{
string err_string = mysql_error(&mysql);
if(err_string.empty())
throw string("MySQL query is error!");
else
throw err_string;
}
cout << "MySQL : " << sql << endl;
MYSQL_RES *result = mysql_store_result(&mysql);
if (!result)
throw string("MySQL not result!");
//Get the number of fields
int num_fields = mysql_num_fields(result);
if(0 == num_fields)
throw string("MySQL fields number is 0!");
//Get the field name
MYSQL_FIELD *fields = mysql_fetch_fields(result);
if (!fields)
throw string("MySQL fields fetch is error!");
for (int i = 0; i < num_fields; i++)
{
cout << " " << fields[i].name;
}
cout << endl;
while (MYSQL_ROW row = mysql_fetch_row(result)) //Getting the whole data content
{
for (int i = 0; i < num_fields; i++)
{
if (NULL == row[i])
{
cout << " NULL";
}
else
{
cout << " " << row[i];
}
}
cout << endl;
}
mysql_free_result(result);
cout << "MySQL is OK." << endl;
}
catch (string &error_msg)
{
cout << error_msg << endl;
}
catch (...)
{
cout << "MySQL operation is error!" << endl;
}
The database data is shown in the following figure
Function API reads data and runs as shown in the following figure.
Read the filtered MySQL command: SELECT phone from zx_users where vname = user2;
The reading results are shown in the following figure.
MySQL C++ API Porting
The reason for separating C++ API from C is that C++ can use C's API, but C++ can encapsulate operations into classes, but boost library support needs to be installed. Header and library files in C++ need to be reconfigured.
Official Document Download:
https://downloads.mysql.com/docs/connector-cpp-en.a4.pdf
Conditions of use:
Windows has installed the corresponding libraries and header files when installing MySQL.
Linux is not included in the installation. You need to download the corresponding library and header files from MySQL.
Official website download address:
https://dev.mysql.com/downloads/connector/cpp/
As shown in the figure below.
Porting MySQL C++ Header File
In order to use API encapsulated by C++ class, it is necessary to re-transplant its header file and library file. After transplantation, the header file of C API can not be used.
Makefile Project
Unzip the downloaded file. After decompression, the project is as follows
~/Tools/mysql_connector_cpp$ tree
.
├── COPYING
├── include
│ ├── cppconn
│ │ ├── build_config.h
│ │ ├── config.h
│ │ ├── connection.h
│ │ ├── datatype.h
│ │ ├── driver.h
│ │ ├── exception.h
│ │ ├── metadata.h
│ │ ├── parameter_metadata.h
│ │ ├── prepared_statement.h
│ │ ├── resultset.h
│ │ ├── resultset_metadata.h
│ │ ├── sqlstring.h
│ │ ├── statement.h
│ │ ├── variant.h
│ │ ├── version_info.h
│ │ └── warning.h
│ ├── mysql_connection.h
│ ├── mysql_driver.h
│ └── mysql_error.h
├── lib
│ ├── libmysqlcppconn.so -> libmysqlcppconn.so.7
│ ├── libmysqlcppconn.so.7 -> libmysqlcppconn.so.7.1.1.9
│ ├── libmysqlcppconn.so.7.1.1.9
│ └── libmysqlcppconn-static.a
├── Licenses_for_Third-Party_Components.txt
└── README
3 directories, 26 files
~/Tools/mysql_connector_cpp$
Copy the header file to the project header file inc
~/inc/Connector.C++ 1.1$ tree
.
├── COPYING.txt
├── include
│ ├── cppconn
│ │ ├── build_config.h
│ │ ├── config.h
│ │ ├── connection.h
│ │ ├── datatype.h
│ │ ├── driver.h
│ │ ├── exception.h
│ │ ├── metadata.h
│ │ ├── parameter_metadata.h
│ │ ├── prepared_statement.h
│ │ ├── resultset.h
│ │ ├── resultset_metadata.h
│ │ ├── sqlstring.h
│ │ ├── statement.h
│ │ ├── variant.h
│ │ ├── version_info.h
│ │ └── warning.h
│ ├── mysql_connection.h
│ ├── mysql_driver.h
│ └── mysql_error.h
├── Licenses_for_Third-Party_Components.txt
└── README.txt
2 directories, 22 files
~/inc/Connector.C++ 1.1$
Add the header file to the Makefile project and edit the Makefile
INC += -I$(DIR)/mysql_connector_cpp/include
Visual Studio Project
Windows has installed the corresponding library and header files when installing MySQLd.
C++ operation header file:
C:\Program Files\MySQL\Connector.C++ 1.1
The file structure is as follows
~/Connector.C++ 1.1$ tree
.
├── COPYING.txt
├── include
│ ├── cppconn
│ │ ├── build_config.h
│ │ ├── config.h
│ │ ├── connection.h
│ │ ├── datatype.h
│ │ ├── driver.h
│ │ ├── exception.h
│ │ ├── metadata.h
│ │ ├── parameter_metadata.h
│ │ ├── prepared_statement.h
│ │ ├── resultset.h
│ │ ├── resultset_metadata.h
│ │ ├── sqlstring.h
│ │ ├── statement.h
│ │ ├── variant.h
│ │ ├── version_info.h
│ │ └── warning.h
│ ├── mysql_connection.h
│ ├── mysql_driver.h
│ └── mysql_error.h
├── lib
│ └── opt
│ ├── mysqlcppconn.dll
│ ├── mysqlcppconn.lib
│ └── mysqlcppconn-static.lib
├── Licenses_for_Third-Party_Components.txt
└── README.txt
4 directories, 25 files
~/Connector.C++ 1.1$
The reference header file is shown in the following figure
Porting MySQL C++ Library Files
Makefile Project
Copy library files to the project library directory
~/open_lib$ tree
.
├── gtest.a
├── libmysqlclient.so
└── MySQL_lib
├── libmysqlcppconn.so
├── libmysqlcppconn.so.7
├── libmysqlcppconn.so.7.1.1.9
├── libmysqlcppconn-static.a
├── libmysql.dll
├── libmysql.lib
├── mysqlclient.lib
├── mysqlcppconn.dll
├── mysqlcppconn.lib
└── mysqlcppconn-static.lib
1 directory, 12 files
~/open_lib$
Library file compilation is added to Makefile project, editing Makefile
MYSQL_LIB += -L$(DIR)/open_lib/MySQL_lib -lmysqlcppconn
Visual Studio Project
Library file location: C: Program Files MySQL Connector. C++ 1.1 lib opt
File location is MySQL installation location.
As shown in the following figure
Copy all library files to the directory of engineering library files
├── open_lib
│ ├── MySQL_lib
│ │ ├── libmysql.dll
│ │ ├── libmysql.lib
│ │ ├── mysqlclient.lib
│ │ ├── mysqlcppconn.dll
│ │ ├── mysqlcppconn.lib
│ │ └── mysqlcppconn-static.lib
The project references library files, as shown in the following figure
Add the project running environment dll. In order to ensure that the program does not depend on the system environment variables after running, it is necessary to put DLL in the output folder of the compiler. If obj is defined as the output folder, DLL is put in the folder. As shown in the figure below.
Reference to boost library
The C++ operation function of MySQL needs the support of boost library, so the compiled boost library header file location and library path are added to the project.
Refer to boost library header files and library files:
Because boost libraries refer to the path of computers, in order to separate the boost libraries from portable engineering configurations, the boost libraries and library files are placed in the VC++ directory of Engineering configurations, as shown in the following figure.
No library files need to be added to the connector after adding.
Because boost libraries are added to system variables, Linux can call the header file directly at compile time.
No need to edit / etc/profile file added
export BOOST_INCLUDE=/home/ghost/Tools/boost_1_60_0:$CPLUS_INCLUDE_PATH
export BOOST_LIBRARY=/home/ghost/Tools/boost_1_60_0/stage/lib:$LIBRARY_PATH
export BOOST_LD_LIBRARY=/home/ghost/Tools/boost_1_60_0/stage/lib:$LD_LIBRARY_PATH
Add MySQL sample
Project adds MySQL sample to test MySQL migration project.
module_MySQLcpp.cpp
#include "module_MySQLcpp.h"
#include <iostream>
#include <string>
#include <vector>
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/driver.h>
#include <cppconn/metadata.h>
#include <cppconn/exception.h>
using namespace std;
using namespace sql;
void TestCppSQL(void)
{
std::string sql = " SELECT * from zx_users where vname = 'user2';";
try
{
sql::mysql::MySQL_Driver *pMysqldriver = mysql::get_mysql_driver_instance();
if (NULL == pMysqldriver)
throw string("MySQL get_mysql_driver_instance is Error.");
sql::Connection *pMysqlconnection = pMysqldriver->connect("localhost",
"zxpro-admin",
"qwerty");
if (NULL == pMysqlconnection)
throw string("MySQL connect is Error.");
Statement *pMysqlstat = pMysqlconnection->createStatement();
if (NULL == pMysqlstat)
throw string("MySQL createStatement is Error.");
if(pMysqlstat->execute("use zx_mysql;"))
throw string("MySQL execute is Error.");
sql::ResultSet *result = pMysqlstat->executeQuery(sql.c_str());
if(NULL == result)
throw string("MySQL executeQuery is Error.");
while (result->next())
{
cout << "-----------------" << endl;
cout << "vname is : " << result->getString("vname").c_str() << endl;
cout << "vpwd is : " << result->getString("vpwd").c_str() << endl;
string pwdtype = result->getString("pwdtype").c_str();
cout << "pwdtype is : " << (pwdtype.empty() ? "NULL" : pwdtype) << endl;
string phone = result->getString("phone").c_str();
cout << "phone is : " << (phone.empty() ? "NULL" : phone) << endl;
cout << "add_time is : " << result->getString("add_time").c_str() << endl;
cout << endl;
}
cout << "MySQL is OK." << endl;
delete result;
result = NULL;
delete pMysqlstat;
pMysqlstat = NULL;
pMysqlconnection->close();
delete pMysqlconnection;
pMysqlconnection = NULL;
}
catch (const SQLException &CMysqlErr)
{
cout << "SQL what :" << CMysqlErr.what() << endl;
cout << "SQL Error code :" << CMysqlErr.getErrorCode() << endl;
cout << "SQL State :" << CMysqlErr.getSQLStateCStr() << endl;
}
catch (const std::string &Err_Msg)
{
cout << Err_Msg << endl;
}
catch (const std::exception &Err)
{
cout << "exception what :"<< Err.what() << endl;
}
catch (...)
{
cout << "MySQL operation is error!" << endl;
}
}
The results of the example project are shown in the following figure.
MySQL C++ API
Header file contains
To use MySQL's interface API, you need to include header files
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/driver.h>
#include <cppconn/metadata.h>
#include <cppconn/exception.h>
//Using MySQL Namespaces
using namespace sql;
MySQL exception class: SQLException
Class descriptions
class CPPCONN_PUBLIC_FUNC SQLException : public std::runtime_error
Class interface call
catch (SQLException &CMysqlErr)
{
cout << "SQL what :" << CMysqlErr.what() << endl;
cout << "SQL Error code :" << CMysqlErr.getErrorCode() << endl;
cout << "SQL State :" << CMysqlErr.getSQLStateCStr() << endl;
}
Class printing, such as entering wrong SQL commands, MySQL function throwing exceptions, the abnormal printing information captured is
Error MySQL instruction: std::string sql = SELECC * from zx_users;;
CSystem is called.
SQL what :You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECC * from zx_users' at line 1
SQL Error code :1064
SQL State :42000
Log in to MySQL: mysql::get_mysql_driver_instance()
Function prototype:
CPPCONN_PUBLIC_FUNC MySQL_Driver * get_driver_instance();
static inline MySQL_Driver * get_mysql_driver_instance() { return get_driver_instance(); }
Definition of Dynamic Library Function
#if defined(_WIN32)
// mysqlcppconn_EXPORTS is added by cmake and defined for dynamic lib build only
#ifdef mysqlcppconn_EXPORTS
#define CPPCONN_PUBLIC_FUNC __declspec(dllexport)
#else
// this is for static build
#ifdef CPPCONN_LIB_BUILD
#define CPPCONN_PUBLIC_FUNC
#else
// this is for clients using dynamic lib
#define CPPCONN_PUBLIC_FUNC __declspec(dllimport)
#endif
#endif
#else
#define CPPCONN_PUBLIC_FUNC
#endif
MySQL Driver Operations Class:
class CPPCONN_PUBLIC_FUNC MySQL_Driver : public sql::Driver
{
boost::scoped_ptr< ::sql::mysql::NativeAPI::NativeDriverWrapper > proxy;
public:
MySQL_Driver();
MySQL_Driver(const ::sql::SQLString & clientLib);
virtual ~MySQL_Driver();
sql::Connection * connect(const sql::SQLString& hostName, //MySQL IP, remote login input IP address of remote login
const sql::SQLString& userName, //log on user
const sql::SQLString& password); //Login password
sql::Connection * connect(sql::ConnectOptionsMap & options);
int getMajorVersion();
int getMinorVersion();
int getPatchVersion();
const sql::SQLString & getName();
void threadInit();
void threadEnd();
private:
/* Prevent use of these */
MySQL_Driver(const MySQL_Driver &);
void operator=(MySQL_Driver &);
};
Steps for C++ Operating Function to Log in to MySQL
sql::mysql::MySQL_Driver *pMysqldriver = mysql::get_mysql_driver_instance();
if (nullptr == pMysqldriver)
throw string("MySQL_Driver is error");
sql::Connection *pMysqlconnection = pMysqldriver->connect("localhost",
"zxpro-admin",
"qwerty");
//Specify a port to log in with this
sql::Connection *pMysqlconnection = pMysqldriver->connect("tcp://localhost:3306", //Designated port
"zxpro-admin",
"qwerty");
if (nullptr == pMysqlconnection)
throw string("MySQL Connection is error!");
Operation MySQL: execute(), executeQuery(), executeUpdate()
Create Statement ()
Statement *pMysqlstat = pMysqlconnection->createStatement();
pMysqlstat->execute("use zx_mysql;");
sql::ResultSet *result = pMysqlstat->executeQuery(sql.c_str());
Function prototype
virtual Statement *createStatement() = 0;
virtual bool execute(const sql::SQLString& sql) = 0;
virtual ResultSet * executeQuery(const sql::SQLString& sql) = 0;
virtual int executeUpdate(const sql::SQLString& sql) = 0;
A key:
sql::SQLString can't receive std::string direct transmission. It needs to call c_str() to transfer to C string.
All three functions can perform operations on MySQL, and their functions can be seen from the return values.
bool execute(): Returns the success or failure of the operation of the statement. ResultSet * executeQuery(): ResultSet returns the class pointer indicating the need to obtain the results of the MySQL statement query int executeUpdate: Returns an integer indicating the number of updates returned
Different execution functions can be invoked according to the needs of the statement:
mysql> select vname, phone from zx_users where pwdtype = 'MD5';
+-----------+-----------+
| vname | phone |
+-----------+-----------+
| user1 | 123456 |
| userpwd | NULL |
+-----------+-----------+
2 rows in set
mysql> update zx_users set phone = 321654 where pwdtype = 'MD5';
Query OK, 2 rows affected
Rows matched: 2 Changed: 2 Warnings: 0
mysql> use zx_mysql;
Database changed
Close MySQL: close()
Call the closing function close() of the class sql::Connection to close MySQL connections.
pMysqlconnection->close();
Read MySQL data: executeQuery()
When this function is called, a pointer to the data result class ResultSet is obtained.
ResultSet class definition header file: Connector. C++ 1.1 include cppconn resultset. H
Result The data content in MySQL field is obtained through the field described by the string, provided that the data type of the field is known and the field type command is viewed: DESC
Where Type is the type of field.
cout << "vname is : " << result->getString("vname").c_str() << endl;
string phone = result->getString("phone").c_str();
cout << "phone is : " << (phone.empty() ? "NULL" : phone) << endl;
ResultSet class read data function prototype
//Getting character data
virtual SQLString getString(const sql::SQLString& columnLabel) const = 0;
//Getting int data
virtual int32_t getInt(const sql::SQLString& columnLabel) const = 0;
virtual uint32_t getUInt(const sql::SQLString& columnLabel) const = 0;
virtual int64_t getInt64(const sql::SQLString& columnLabel) const = 0;
virtual uint64_t getUInt64(const sql::SQLString& columnLabel) const = 0;
//Getting binary data
virtual std::istream * getBlob(const sql::SQLString& columnLabel) const = 0;
The field description string can not pass string directly, so it needs to call c_str() to transfer to C string.
Test program
std::string sql = "SELECT * from zx_users;";
try
{
………
sql::ResultSet *result = pMysqlstat->executeQuery(sql.c_str());
if(NULL == result)
throw string("MySQL executeQuery is Error.");
while (result->next())
{
cout << "-----------------" << endl;
cout << "vname is : " << result->getString("vname").c_str() << endl;
cout << "vpwd is : " << result->getString("vpwd").c_str() << endl;
string pwdtype = result->getString("pwdtype").c_str();
cout << "pwdtype is : " << (pwdtype.empty() ? "NULL" : pwdtype) << endl;
string phone = result->getString("phone").c_str();
cout << "phone is : " << (phone.empty() ? "NULL" : phone) << endl;
cout << "add_time is : " << result->getString("add_time").c_str() << endl;
cout << endl;
}
cout << "MySQL is OK." << endl;
delete result;
result = NULL;
delete pMysqlstat;
pMysqlstat = NULL;
pMysqlconnection->close();
delete pMysqlconnection;
pMysqlconnection = NULL;
}
catch (const SQLException &CMysqlErr)
{
cout << "SQL what :" << CMysqlErr.what() << endl;
cout << "SQL Error code :" << CMysqlErr.getErrorCode() << endl;
cout << "SQL State :" << CMysqlErr.getSQLStateCStr() << endl;
}
catch (const std::string &Err_Msg)
{
cout << Err_Msg << endl;
}
catch (const std::exception &Err)
{
cout << "exception what :"<< Err.what() << endl;
}
catch (...)
{
cout << "MySQL operation is error!" << endl;
}
The database data is shown in the following figure
Function API reads data and runs as shown in the following figure.