MySQL-C++封装类
参考:https://blog.csdn.net/daoming1112/article/details/54710743
MySQLInterface.h:
-
// MySQLInterface
-
-
// 功能描述:实现对MySQL访问操作的封装
-
-
-
-
-
-
-
-
-
-
-
// 引入相关库
-
-
-
-
-
-
-
// 定义MySQL连接信息
-
typedef struct
-
{
-
char* server;
-
char* user;
-
char* password;
-
char* database;
-
int port;
-
}MySQLConInfo;
-
-
class MySQLInterface
-
{
-
public:
-
MySQLInterface();
-
virtual ~MySQLInterface();
-
-
void SetMySQLConInfo(char* server, char* username, char* password, char* database, int port);// 设置连接信息
-
bool Open(); // 打开连接
-
void Close(); // 关闭连接
-
-
bool Select(const std::string& Querystr, std::vector<std::vector<std::string> >& data); // 读取数据
-
bool Query(const std::string& Querystr); // 其他操作
-
int GetInsertID(const std::string& Querystr);// 插入并获取插入的ID,针对自动递增ID
-
void ErrorIntoMySQL(); // 错误消息
-
-
public:
-
int ErrorNum; // 错误代号
-
const char* ErrorInfo; // 错误提示
-
-
private:
-
MySQLConInfo MysqlConInfo; // 连接信息
-
MYSQL MysqlInstance; // MySQL对象
-
MYSQL_RES *Result; // 用于存放结果
-
};
-
-
MySQLInterface.cpp:
-
-
-
-
-
MySQLInterface::MySQLInterface() :
-
ErrorNum(0), ErrorInfo("ok")
-
{
-
mysql_library_init(0, NULL, NULL);
-
mysql_init(&MysqlInstance);
-
-
// 设置字符集,否则无法处理中文
-
mysql_options(&MysqlInstance, MYSQL_SET_CHARSET_NAME, "gbk");
-
}
-
-
MySQLInterface::~MySQLInterface()
-
{
-
}
-
-
// 设置连接信息
-
void MySQLInterface::SetMySQLConInfo(char* server, char* username, char* password, char* database, int port)
-
{
-
MysqlConInfo.server = server;
-
MysqlConInfo.user = username;
-
MysqlConInfo.password = password;
-
MysqlConInfo.database = database;
-
MysqlConInfo.port = port;
-
}
-
-
// 打开连接
-
bool MySQLInterface::Open()
-
{
-
if (mysql_real_connect(&MysqlInstance, MysqlConInfo.server, MysqlConInfo.user,
-
MysqlConInfo.password, MysqlConInfo.database, MysqlConInfo.port, 0, 0) != NULL)
-
{
-
return true;
-
}
-
else
-
{
-
ErrorIntoMySQL();
-
return false;
-
}
-
}
-
-
// 断开连接
-
void MySQLInterface::Close()
-
{
-
mysql_close(&MysqlInstance);
-
}
-
-
//读取数据
-
bool MySQLInterface::Select(const std::string& Querystr, std::vector<std::vector<std::string> >& data)
-
{
-
if (0 != mysql_query(&MysqlInstance, Querystr.c_str()))
-
{
-
ErrorIntoMySQL();
-
return false;
-
}
-
-
Result = mysql_store_result(&MysqlInstance);
-
-
// 行列数
-
int row = mysql_num_rows(Result);
-
int field = mysql_num_fields(Result);
-
-
MYSQL_ROW line = NULL;
-
line = mysql_fetch_row(Result);
-
-
int j = 0;
-
std::string temp;
-
std::vector<std::vector<std::string> >().swap(data);
-
while (NULL != line)
-
{
-
std::vector<std::string> linedata;
-
for (int i = 0; i < field; i++)
-
{
-
if (line[i])
-
{
-
temp = line[i];
-
linedata.push_back(temp);
-
}
-
else
-
{
-
temp = "";
-
linedata.push_back(temp);
-
}
-
}
-
line = mysql_fetch_row(Result);
-
data.push_back(linedata);
-
}
-
return true;
-
}
-
-
// 其他操作
-
bool MySQLInterface::Query(const std::string& Querystr)
-
{
-
if (0 == mysql_query(&MysqlInstance, Querystr.c_str()))
-
{
-
return true;
-
}
-
ErrorIntoMySQL();
-
return false;
-
}
-
-
// 插入并获取插入的ID,针对自动递增ID
-
int MySQLInterface::GetInsertID(const std::string& Querystr)
-
{
-
if (!Query(Querystr))
-
{
-
ErrorIntoMySQL();
-
return ERROR_QUERY_FAIL;
-
}
-
// 获取ID
-
return mysql_insert_id(&MysqlInstance);
-
}
-
-
//错误信息
-
void MySQLInterface::ErrorIntoMySQL()
-
{
-
ErrorNum = mysql_errno(&MysqlInstance);
-
ErrorInfo = mysql_error(&MysqlInstance);
-
}
Example
#include <iostream> using namespace std;
#include "MySQLInterface.h"
int _tmain(int argc, _TCHAR* argv[]) { MySQLInterface MySQLInterface; MySQLInterface.SetMySQLConInfo("localhost", "root", "123456", "world", 337); if (!MySQLInterface.Open()) { std::cout << MySQLInterface.ErrorNum << " : " << MySQLInterface.ErrorInfo << std::endl; }
// 读取数据 std::vector<std::vector<std::string> > data; std::string sqlstr = "SELECT `ID`,`Name`,`CountryCode`,`District` FROM `world`.`city` LIMIT 10"; MySQLInterface.Select(sqlstr, data);
// 显示数据 for (unsigned int i = 0; i < data.size(); ++i) { for (unsigned int j = 0; j < data[0].size(); ++j) { cout << data[i][j] << "\t\t"; } cout << endl; }
// 其他操作 sqlstr = "CREATE TABLE IF NOT EXISTS `new_paper` ("; sqlstr += " `NewID` int(11) NOT NULL AUTO_INCREMENT,"; sqlstr += " `NewCaption` varchar(40) NOT NULL,"; sqlstr += " `NewContent` text,"; sqlstr += " `NewTime` datetime DEFAULT NULL,"; sqlstr += " PRIMARY KEY(`NewID`)"; sqlstr += " ) ENGINE = InnoDB DEFAULT CHARSET = utf8";
if (!MySQLInterface.Query(sqlstr)) { std::cout << MySQLInterface.ErrorNum << " : " << MySQLInterface.ErrorInfo << std::endl; }
MySQLInterface.Close();
system("pause"); return 0; } |
错误提示
MFC (CString)
if (!m_MySQLInter.Open()) // 连接失败 { CString strError = _T(""); USES_CONVERSION; strError.Format(_T("打开数据库失败...\n%d : %s"), m_MySQLInter.ErrorNum, A2W(m_MySQLInter.ErrorInfo)); ::MessageBox(GetSafeHwnd(), strError, _T("系统提示"), MB_ICONEXCLAMATION | MB_OK); return; } |
Win32
if(!m_MySQLInter.Open())
{
std::cout<< m_MySQLInter.ErrorNum << " : " <<m_MySQLInter.ErrorInfo << std::endl;
return;
}
类型转换
Std::string to char*
// 类型转换 char* pDatabase = new char[strlen(database.c_str()) + 1]; strcpy(pDatabase, database.c_str()); char* pPassword = new char[strlen(password.c_str()) + 1]; strcpy(pPassword, password.c_str()); char* pUserName = new char[strlen(usename.c_str()) + 1]; strcpy(pUserName, usename.c_str()); char* pServer = new char[strlen(server.c_str()) + 1]; strcpy(pServer, server.c_str());
m_MySQLInter.SetMySQLConInfo(pServer, pUserName, pPassword, pDatabase, port); |
CString to char*
USES_CONVERSION; m_MySQLInter.SetMySQLConInfo(W2A(m_strServer), W2A(m_strUserName), W2A(m_strPassword), "log", _ttoi(m_strPort));
if (!m_MySQLInter.Open()) // 连接失败 { CString strError = _T(""); USES_CONVERSION; strError.Format(_T("打开数据库失败...\n%d : %s"), m_MySQLInter.ErrorNum, A2W(m_MySQLInter.ErrorInfo)); ::MessageBox(GetSafeHwnd(), strError, _T("系统提示"), MB_ICONEXCLAMATION | MB_OK); return; } |