Reference: https://blog.csdn.net/daoming1112/article/details/54710743
MySQLInterface.h:
-
// MySQLInterface
-
-
// Function Description: encapsulate the realization of access operations MySQL
-
-
-
-
-
-
-
-
-
-
-
// imports related libraries
-
-
-
-
-
-
-
// define the MySQL connection information
-
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) ; // set the connection information
-
BOOL the Open () ; // open connection
-
void the Close () ; // close the connection
-
-
bool Select(const std::string& Querystr, std::vector<std::vector<std::string> >& data); // 读取数据
-
BOOL Query ( const STD :: String & queryStr) ; // else
-
int GetInsertID ( const std :: String & queryStr) ; // get inserted and the insertion of ID, for auto-increment ID
-
void ErrorIntoMySQL () ; // Error Messages
-
-
public:
-
int ErrorNum; // error code
-
const char * ErrorInfo; // error
-
-
private:
-
MysqlConInfo MySQLConInfo; // Connection Information
-
MysqlInstance MYSQL; // MySQL objects
-
* The Result MYSQL_RES; // for the result
-
};
-
-
MySQLInterface.cpp:
-
-
-
-
-
MySQLInterface::MySQLInterface() :
-
ErrorNum( 0), ErrorInfo( "ok")
-
{
-
mysql_library_init( 0, NULL, NULL);
-
mysql_init(&MysqlInstance);
-
-
// set the character set, or can not handle Chinese
-
mysql_options(&MysqlInstance, MYSQL_SET_CHARSET_NAME, "gbk");
-
}
-
-
MySQLInterface::~MySQLInterface()
-
{
-
}
-
-
// set the connection information
-
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;
-
}
-
-
// open connection
-
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;
-
}
-
}
-
-
// Disconnect
-
void MySQLInterface::Close()
-
{
-
mysql_close(&MysqlInstance);
-
}
-
-
// read data
-
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);
-
-
// ranks number
-
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;
-
}
-
-
// other operations
-
bool MySQLInterface::Query( const std:: string& Querystr)
-
{
-
if ( 0 == mysql_query(&MysqlInstance, Querystr.c_str()))
-
{
-
return true ;
-
}
-
ErrorIntoMySQL ();
-
return false;
-
}
-
-
// insert and get inserted ID, for auto-increment ID
-
int MySQLInterface::GetInsertID( const std:: string& Querystr)
-
{
-
if (!Query(Querystr))
-
{
-
ErrorIntoMySQL ();
-
return ERROR_QUERY_FAIL;
-
}
-
// Get ID
-
return mysql_insert_id(&MysqlInstance);
-
}
-
-
// error message
-
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; }
// read data std::vector<std::vector<std::string> > data; std::string sqlstr = "SELECT `ID`,`Name`,`CountryCode`,`District` FROM `world`.`city` LIMIT 10"; MySQLInterface.Select(sqlstr, data);
// Display 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; } |