最近学到了mysql,对mysql进行了一次简单的封装,可后面逐渐修改
mysqlOp.h
#ifndef __INCLUDE_MYSQLOP_H__
#define __INCLUDE_MYSQLOP_H__
#include <mysql/mysql.h>
#include <vector>
#include <string>
class MysqlOp
{
public:
MysqlOp();
~MysqlOp();
public:
//connect sql
bool ConnectSql(const char* mysql_ip, int port, const char* users, const char* pwd, const char* db);
//query with answer
bool QuerySql(const char* sql, std::vector<std::vector<std::string> > & data);
//execute with no answer
bool ExecuteSql(const char* sql);
//change database
bool SelectDatabase(const char* dbName);
//error prompt
const char* GetLastErrorPrompt();
private:
MYSQL mysql_;
};
#endif//__INCLUDE_MYSQLOP_H__
mysqlOp.cpp
#include "mysqlop.h"
#include <cstring>
#include <cassert>
MysqlOp::MysqlOp()
{
mysql_init(&mysql_);
}
MysqlOp::~MysqlOp()
{
mysql_close(&mysql_);
}
//connect sql
bool MysqlOp::ConnectSql(const char* mysql_ip, int port, const char* users, const char* pwd, const char* db)
{
MYSQL* p = mysql_real_connect(&mysql_, mysql_ip, users, pwd, db, port, 0, 0);
return NULL != p;
}
//query with answer
bool MysqlOp::QuerySql(const char* sql, std::vector<std::vector<std::string> > & data)
{
//assert(sql);
if (!ExecuteSql(sql))
{
return false;
}
MYSQL_RES *res = NULL;
res = mysql_store_result(&mysql_);
if (res == NULL)
{
return false;
}
int column_len = res->field_count;
MYSQL_ROW row;
while (NULL != (row = mysql_fetch_row(res)))
{
std::vector<std::string> strRow;
for (int i = 0; i < column_len; i++)
{
strRow.push_back(row[i]);
}
data.push_back(strRow);
}
mysql_free_result(res);
return true;
}
//execute with no answer
bool MysqlOp::ExecuteSql(const char* sql)
{
//assert(sql);
int nRet = mysql_real_query(&mysql_, sql, (unsigned long)strlen(sql));
return nRet == 0;
}
//change database
bool MysqlOp::SelectDatabase(const char* dbName)
{
//assert(dbName);
int ret = mysql_select_db(&mysql_, dbName);
return ret == 0;
}
//error prompt
const char* MysqlOp::GetLastErrorPrompt()
{
const char* error_string = mysql_error(&mysql_);
return error_string;
}
//测试代码:
#include "mysqlop.h"
#include <vector>
#include <string>
#include <iostream>
int main()
{
MysqlOp mysqlOp;
if (!mysqlOp.ConnectSql("192.168.196.130", 3306, "root", "123456", NULL))
{
printf("connect mysql error!---%s\n", mysqlOp.GetLastErrorPrompt());
return 0;
}
const char* query_statment = "show databases";
std::vector<std::vector<std::string>> res;
if (mysqlOp.QuerySql(query_statment, res))
{
decltype(res.begin()) it = res.begin();
for (; it != res.end(); ++it)
{
std::vector<std::string> oneline = *it;
decltype(oneline.begin()) fieldString = oneline.begin();
for (; fieldString != oneline.end(); ++fieldString)
{
std::cout << *fieldString << std::endl;
}
}
}
return 0;
}
需要用到其他功能,后续添加即可