#include "MysqlConn.h"
|
#include <regex>
|
// ³õʼ»¯Á¬½Ó
|
MysqlConn::MysqlConn() {
|
mysql_ = mysql_init( mysql_ );
|
// ÉèÖÃ×Ö·û¼¯
|
if( mysql_ ) mysql_set_character_set(mysql_ , "gbk");
|
}
|
|
// Á¬½ÓÊý¾Ý¿â
|
bool MysqlConn::connect( std::string ip, std::string userName, std::string passwd, std::string db, int port ) {
|
mysql_ = mysql_real_connect(mysql_, ip.c_str(), userName.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0);
|
if (!mysql_) {
|
return false;
|
}
|
return true;
|
}
|
|
// ÊÍ·Å×ÊÔ´
|
MysqlConn::~MysqlConn() {
|
if (mysql_) {
|
mysql_close(mysql_);
|
mysql_ = nullptr;
|
}
|
freeRes();
|
}
|
// ¸üÐÂÊý¾Ý
|
bool MysqlConn::update( std::string sql ) {
|
if (!isSqlSafe(sql))
|
{
|
return false;
|
}
|
int ret = mysql_query( mysql_ , sql.c_str());
|
if( ret != 0 ){
|
return false;
|
}
|
return true;
|
}
|
|
// ²éѯÊý¾Ý¿â
|
bool MysqlConn::query(std::string sql) {
|
freeRes( );
|
if (!isSqlSafe(sql))
|
{
|
return false;
|
}
|
int ret = mysql_query(mysql_, sql.c_str());
|
if (ret != 0) return false;
|
|
// »ñÈ¡²éѯ½á¹û
|
res_ = mysql_store_result(mysql_);
|
if (!res_) return false;
|
return true;
|
}
|
|
// µÃµ½½á¹û¼¯
|
bool MysqlConn::getResult() {
|
if (res_) {
|
row_ = mysql_fetch_row(res_);
|
if(row_) return true;
|
}
|
return false;
|
}
|
|
// »ñÈ¡½á¹û¼¯µÄ×Ö¶Î
|
std::string MysqlConn::getField( int index ) {
|
int cols = mysql_num_fields(res_);
|
if ( index >= cols || index < 0 ) return std::string("");
|
|
char* value = row_[index];
|
unsigned long len = mysql_fetch_lengths(res_)[index];
|
return std::string(value, len);
|
}
|
|
// ÊÂÎñ²Ù×÷
|
bool MysqlConn::transaction() {
|
return mysql_autocommit(mysql_ ,false );
|
}
|
|
// Ìá½»ÊÂÎñ
|
bool MysqlConn::commit() {
|
return mysql_commit(mysql_);
|
}
|
|
// ÊÂÎñ»Ø¹ö
|
bool MysqlConn::rollback() {
|
return mysql_rollback(mysql_);
|
}
|
|
void MysqlConn::refreshActiveTime()
|
{
|
activeTime_ = std::chrono::steady_clock::now();
|
}
|
|
long long MysqlConn::getActiveTime()
|
{
|
// ÄÉÃ×
|
std::chrono::nanoseconds nased = std::chrono::steady_clock::now() - activeTime_;
|
// ת»»³ÉºÁÃ×
|
std::chrono::microseconds millsed = std::chrono::duration_cast<std::chrono::microseconds>( nased );
|
return millsed.count( ); // ¶àÉÙºÁÃë
|
}
|
// °²È«Ð£ÑéʵÏÖ£¬ÕâÀï¼òµ¥Ê¹ÓÃÕýÔò±í´ïʽÅжÏÊÇ·ñ°üº¬Î£ÏÕ×Ö·û
|
bool MysqlConn::isSqlSafe(const std::string& sql)
|
{
|
std::regex dangerousPattern(".*(['\";\\-+=]).*");
|
return!std::regex_search(sql, dangerousPattern);
|
}
|
|
void MysqlConn::freeRes() {
|
if (res_) {
|
mysql_free_result(res_);
|
res_ = nullptr;
|
}
|
}
|