Example implementation of C++ operation MySQL

  • 2020-08-22 22:27:41
  • OfStack

Windows version:

Copy and paste libmysql.dll, libmysql.lib, mysql.h into the project file, or add the path to the include directory and library directory in the project Settings


#include <iostream>
#include<iomanip>
#include "winsock.h" 
#include "mysql.h" 
#pragma comment(lib,"libmySQL.lib")

using namespace std;

int main()
{
 MYSQL* m_sqlCon;
 MYSQL_RES* res_set;
 MYSQL_ROW row;
 MYSQL_FIELD* field;

 m_sqlCon = mysql_init((MYSQL*)0);
 if (!mysql_real_connect(m_sqlCon, "localhost", "root", "123456", "test", 3306, NULL, 0))
 {
  cerr << "Failed to connect to database: Error: " << mysql_error(m_sqlCon) << endl;
 }
 else
 {
  cerr << "Successfully connected to Database." << endl;
  cout << endl;

  string pQuery = "select * from my_table";
  int status = mysql_real_query(m_sqlCon, pQuery.c_str(), (UINT)strlen(pQuery.c_str()));  // Type the command 

  res_set = mysql_store_result(m_sqlCon);

  field = mysql_fetch_fields(res_set); // Gets all column names 
  int field_count = mysql_field_count(m_sqlCon);  // Get the number of columns 

             
  for (int i = 0; i < field_count; i++) // Output all column names 
  {
   cout << setw(15) << field[i].name; // A total of 15 " 
  }
  cout << endl;

  int row_count = mysql_num_rows(res_set); // Get number of rows 

  while (row = mysql_fetch_row(res_set))  // Output all rows 
  {
   for (int i = 0; i < field_count; i++)
   {
    cout << setw(15) << row[i];
   }
   cout << endl;
  }
 }

 mysql_close(m_sqlCon);

 system("pause");
 return 0;
}

API interface for MySQL:

mysql_affected_rows() returns the number of rows affected by the latest UPDATE, DELETE, or INSERT queries.
mysql_close() closes 1 server connection.
mysql_connect() connects to 1 MySQL server. This function is not recommended; Use mysql_real_connect() instead.
mysql_change_user() changes the user and database on 1 open connection.
mysql_create_db() creates 1 database. This function is not recommended; Instead, use the SQL command CREATE DATABASE.
mysql_data_seek() searches for 1 arbitrary row in 1 query result set.
mysql_debug() makes 1 DBUG_PUSH with the given string.
mysql_drop_db() dumps 1 database. This function is not recommended; Instead, use the SQL command DROP DATABASE.
mysql_dump_debug_info() lets the server write debugging information to the log file.
mysql_eof() determines whether the last line of a result set has been read. This function is opposed; mysql_errno() or mysql_error() can be used inversely.
mysql_errno() returns the error number of the MySQL function that was recently called.
mysql_error() returns an error message for the MySQL function that was recently called.
mysql_escape_string() escape special characters for strings used in SQL statements.
mysql_fetch_field() returns the type of the next table field.
mysql_fetch_field_direct () returns the type of 1 table field, giving 1 field number.
mysql_fetch_fields() returns an array of all field structures.
mysql_fetch_lengths() returns the length of all columns in the current row.
mysql_fetch_row() gets the next row from the result set.
mysql_field_seek() places the column cursor on one of the specified columns.
mysql_field_count() returns the number of result columns for the most recent query.
mysql_field_tell() returns the location of the field cursor used for the last mysql_fetch_field().
mysql_free_result() frees the memory used by 1 result set.
mysql_get_client_info() returns customer version information.
mysql_get_host_info() returns 1 string describing the connection.
mysql_get_proto_info() returns the version of the protocol used for the connection.
mysql_get_server_info() returns the server version number.
mysql_info() returns information about the most recently executed query.
mysql_init() gets or initializes 1 MYSQL structure.
mysql_insert_id() returns ID with the previous query generated for one AUTO_INCREMENT column.
mysql_kill() kills 1 given thread.
mysql_list_dbs() returns the database name matching a simple regular expression.
mysql_list_fields() returns the column name matching a simple regular expression.
mysql_list_processes() returns a table for the current server thread.
mysql_list_tables() returns the table name matching a simple regular expression.
mysql_num_fields() returns the number of columns that weigh 1 result set.
mysql_num_rows() returns the number of rows in 1 result set.
mysql_options() sets the connection option for mysql_connect().
mysql_ping() checks that the connection to the server is working and reconnects if necessary.
mysql_query() executes the SQL query specified as a string with an empty end.
mysql_real_connect() connects to 1 MySQL server.
mysql_real_query() executes the SQL query specified as a string with a count.
mysql_reload() tells the server to reload the authorization table.
mysql_row_seek() searches for rows in the result set, using the value returned from mysql_row_tell().
mysql_row_tell() returns the cursor position of the row.
mysql_select_db() connects to 1 database.
mysql_shutdown() shut down the database server.
mysql_stat() returns the server status as a string.
mysql_store_result() retrieves 1 complete set of results to the customer.
mysql_thread_id() returns ID for the current thread.
mysql_use_result() initializes the retrieval of a 1-row-1-row result set.

Via MySQL Connector C++

MySQL C++ Driver is implemented based on the JDBC specification

MySQL Connector/C++ is an MySQL connector developed by Sun Microsystems. It provides an OO-based programming interface with a database driver to operate the MySQL server.

Unlike many other existing C++ interface implementations, Connector/C++ follows the JDBC specification. In other words, Connector/C++ Driver's API is mainly based on THE Java language JDBC interface. JDBC is the standard industrial interface for THE java language to connect to various databases.

Connector/C++ implements most of the JDBC specification. If developers of C++ programs are familiar with JDBC programming, they will get started quickly.

MySQL Connector/C++ requires the boost library to be installed and configured. The boost library installation compilation is not covered here

1. Create a new empty project

Add F:\MySQL\Connector C++ 1.1.3\lib\opt to the project's library directory (depending on the path)

Add F:\MySQL C++ 1.1.3\include ++ to the inclusion directory of VC++ (depending on the path),

Add F:\boost\boost_1_55_0 to the inclusion directory of VC++ (depending on the path)

Add mysqlcppconn.lib to linker -- > Input - > Additional dependencies

Similarly, if the mysql you are using is 64-bit, you will need to change the project's solution platform from win32 to x64

Copy F:\MySQL C++ 1.1.3\lib\opt (depending on the path) to the project, and the.cpp,.h file under the same path
Copy ES33en :\MySQL\ Server 5.6\ ES3447en (depending on the specific path) to the project, and the.cpp,.h file in the same path (configuration completed)


#include <iostream>
#include <map>
#include <string>
#include <memory>
#include "mysql_driver.h"
#include "mysql_connection.h"
#include "cppconn/driver.h"
#include "cppconn/statement.h"
#include "cppconn/prepared_statement.h"
#include "cppconn/metadata.h"
#include "cppconn/exception.h"
 
using namespace std;
using namespace sql;
 
int main()
{
  sql::mysql::MySQL_Driver *driver = 0;
  sql::Connection *conn = 0;
 
  try
  {
    driver = sql::mysql::get_mysql_driver_instance();
    conn = driver->connect("tcp://localhost:3306/booktik", "root", "123456");
    cout << " The connection is successful " << endl;
  }
  catch (...)
  {
    cout << " The connection fails " << endl;
  }
  sql::Statement* stat = conn->createStatement();
  stat->execute("set names 'gbk'");
  ResultSet *res;
  res = stat->executeQuery("SELECT * FROM BOOK");
  while (res->next())
  {
    cout << "BOOKNAME:" << res->getString("bookname") << endl;
    cout << "  SIZE:" << res->getString("size") << endl;
  }
  if (conn != 0)
  {
    delete conn;
  }
}

Linux version:


#include <iostream>
#include <string>
#include "/usr/include/mysql/mysql.h"

using namespace std;

class MyDb 
{
public:
 MyDb();
 ~MyDb();
 bool initDB(string host, string user,string pwd,string db_name, int port);
 bool exeSQL(string sql);

private:
 MYSQL *mysql;
 MYSQL_RES *result;
 MYSQL_ROW row;
};

MyDb::MyDb()
{
 mysql = mysql_init(NULL);

 if(!mysql) {
  cout<<"Error:"<<mysql_error(mysql);
  exit(1);
 }
}

MyDb::~MyDb()
{
 if(mysql) {
  mysql_close(mysql);
 }
}

bool MyDb::initDB(string host, string user, string passwd, string db_name, int port = 3306)
{
 mysql = mysql_real_connect(mysql, host.c_str(),
    user.c_str(), passwd.c_str(), db_name.c_str(), port, NULL, 0);
 if(!mysql) {
  cout << "Error: " << mysql_error(mysql);
  exit(1);
 }

 return true;
}

bool MyDb::exeSQL(string sql)
{
 //mysql_query() Return on successful execution 0, Failure to execute returns no 0 Value. 
 if (mysql_query(mysql,sql.c_str())) {
  cout<<"Query Error: "<<mysql_error(mysql);
  return false;
 }

 result = mysql_store_result(mysql);

 if (result) {
  // Gets the total number of fields, or columns, in the result set 
  int num_fields = mysql_num_fields(result);
  unsigned long long num_rows = mysql_num_rows(result);

  for(unsigned long long i = 0; i < num_rows; i++) {
   row = mysql_fetch_row(result);
   if(!row) {
    break;
   }

   for(int j=0;j<num_fields;j++) {
    cout<<row[j]<<"\t\t";
   }
   cout<<endl;
  }
 } else {
  // Represents the execution of update,insert,delete Class 
  if (mysql_field_count(mysql) == 0) {
   //  return update,insert,delete The number of rows affected 
   unsigned long long num_rows = mysql_affected_rows(mysql);

   return num_rows;
  } else {
   cout << "Get result error: " << mysql_error(mysql);
   return false;
  }
 }

 return true;
}

int main() 
{
 MyDb db;

 string host = "127.0.0.1";
 string user = "skynet";
 string passwd = "123456";
 string dbName = "skynet";
 int port = 3306;

 // Connect to database 
 bool conn = db.initDB(host, user, passwd, dbName, port);

 if (!conn) {
  cout<<"connect fails\n";
 }

 cout<<"ok" <<endl;

 // Read all the user information and output it. 
 string sql = "SELECT * from test;";
 db.exeSQL(sql);

 return 0;
}

Related articles: