1 Overview
C++ can connect to Mysql database through the following methods:
The first method is to use the ADO connection,
The second method is to use mysql's own api function to connect.
This time we mainly introduce the second method.
2. Download and install Mysql
MySQL download address: https://dev.mysql.com/downloads/; installation will not be introduced here.
If mysql is already installed, but the connection support library is missing, just download the library. download link:
https://dev.mysql.com/downloads/connector/
3. Create a Vs project, add and set project properties
Project selection properties, enter C/C++ => General => Additional include directories, add D:\your mysql installation directory or library directory\include
Properties page, go to Linker => General => Additional Library Directories, add D:\ your mysql installation directory or library directory \lib
Drag libmysql.lib directly into the project.
4. Test procedure
// mysql_t.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include <stdio.h>
#include <WinSock.h> //Be sure to include this, or winsock2.h
#include "mysql.h"
#include <Windows .h>
#include <string>
#include <memory>
//#include <boost\serialization\singleton.hpp>
#pragma comment(lib,"wsock32.lib")
#pragma comment(lib,"libmysql.lib")
using namespace std;
class CSqlHelper
{
public:
CSqlHelper()
{
Init();
}
~CSqlHelper()
{
FreeConnect();
}
public:
void Init()
{
mysql_init(&m_mysql); //Connect mysql, database
}
bool ConnectDatabase(); //Function declaration
void FreeConnect();
bool QueryDatabase1(); //Query 1
bool QueryDatabase2(); //Query 2
bool InsertData(const char* strSql);
bool ModifyData(const char* strSql);
bool DeleteData(const char* strSql);
public:
MYSQL m_mysql; //mysql connection
MYSQL_FIELD *fd; //field column array
char field[32][32]; // A two-dimensional array of field names
MYSQL_RES *res; //This structure represents a query result set of the returned row
MYSQL_ROW column; //A type-safe representation of row data, representing the column of the data row
char query[150 ]; //Query statement
};
typedef shared_ptr<CSqlHelper> CSqlHelperPtr;
int _tmain(int argc, _TCHAR* argv[])
{
CSqlHelperPtr mysql(new CSqlHelper());
if(!mysql->ConnectDatabase())
{
cout<<"Failed to connect to database!"<<endl;
}
return 0;
}
//Connect database
bool CSqlHelper::ConnectDatabase()
{
//If false is returned, the connection fails, and if true is returned, the connection is successful
if (!(mysql_real_connect(&m_mysql,"localhost", "root", "123456", "databasename", 3306, NULL,0))) //The middle is Host, username, password, database name, port number (default 0 or 3306, etc. can be written), which can be written as parameters and then passed in
{
printf( "Error connecting to database:%s\n",mysql_error(&m_mysql));
return false;
}
else
{
printf("Connected...\n");
return true;
}
}
//Release resources
void CSqlHelper::FreeConnect()
{
//Release resources
mysql_free_result(res);
mysql_close(&m_mysql);
}
/************************** *Database operation *********************************/
//In fact, all database operations are written first sql statement, and then use mysql_query(&mysql,query) to complete, including creating a database or table, adding, deleting, modifying and
querying//query data
bool CSqlHelper::QueryDatabase1()
{
sprintf(query, "select * from user"); // Execute the query statement, here is the query all, user is the table name, without quotation marks, you can also use strcpy
mysql_query(&m_mysql,"set names gbk"); //Set the encoding format (SET NAMES GBK also works), otherwise Chinese under cmd Garbled
// returns 0 if the query is successful, and returns 1 if the query fails
if(mysql_query(&m_mysql, query)) //Execute the SQL statement
{
printf("Query failed (%s)\n",mysql_error(&m_mysql));
return false;
}
else
{
printf("query success\n");
}
//Get the result set
if (!(res=mysql_store_result(&m_mysql))) //Get the result set returned after the end of the sql statement
{
printf("Couldn 't get result from %s\n", mysql_error(&m_mysql));
return false;
}
//print the number of data lines
printf("number of dataline returned: %d\n",mysql_affected_rows(&m_mysql));
//get Field information
char *str_field[32]; //Define a string array to store field information
for(int i=0;i<4;i++) //Get the field name when the number of fields is known
{
str_field[i ]=mysql_fetch_field(res)->name;
}
for(int i=0;i< 4;i++) //print field
printf("%10s\t",str_field[i]);
printf("\n");
//print the fetched data
while (column = mysql_fetch_row(res)) //if the number of fields is known, get and print the next line
{
printf("%10s\t%10s\t%10s\t%10s\n", column[0], column[1], column[2],column[3]); //column is Column array
}
return true;
}
bool CSqlHelper::QueryDatabase2()
{
mysql_query(&m_mysql,"set names gbk");
//return 0 if the query is successful, return 1 if the query fails
if(mysql_query(&m_mysql, "select * from user") ) //Execute SQL statement
{
printf("Query failed (%s)\n",mysql_error(&m_mysql));
return false;
}
else
{
printf("query success\n");
}
res=mysql_store_result(&m_mysql);
//打印数据行数
printf("number of dataline returned: %d\n",mysql_affected_rows(&m_mysql));
for(int i=0;fd=mysql_fetch_field(res);i++) //获取字段名
strcpy(field[i],fd->name);
int j=mysql_num_fields(res); // 获取列数
for(int i=0;i<j;i++) //打印字段
printf("%10s\t",field[i]);
printf("\n");
while(column=mysql_fetch_row(res))
{
for(int i=0;i<j;i++)
printf("%10s\t",column[i]);
printf("\n");
}
return true; //insert data
}
bool CSqlHelper::InsertData(const char* strSql)
{
//sprintf(query, "insert into user values (NULL, 'Lilei', 'wyt2588zs','[email protected]');");
if(mysql_query(&m_mysql, strSql)) //执行SQL语句
{
printf("Query failed (%s)\n",mysql_error(&m_mysql));
return false;
}
else
{
printf("Insert success\n");
return true;
}
}
//修改数据
bool CSqlHelper::ModifyData(const char* strSql)
{
//sprintf(query, "update user set email='[email protected]' where name='Lilei'"); {
if(mysql_query(&m_mysql, strSql)) //Execute SQL statement
printf("Query failed (%s)\n",mysql_error(&m_mysql));
return false;
}
else
{
printf("Insert success\n");
return true;
}
}
//删除数据
bool CSqlHelper::DeleteData(const char *strSql)
{
/*sprintf(query, "delete from user where id=6");*/
// char query[100];
//printf("please input the sql:\n");
// gets(query); //这里手动输入sql语句
if(mysql_query(&m_mysql, strSql)) //执行SQL语句
{
printf("Query failed (%s)\n",mysql_error(&m_mysql));
return false;
}
else
{
printf("Insert success\n");
return true;
}
}