| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- #include "SqlWrite.h"
- #include <thread>
- #include "Log.h"
- #include "JdbcHelper.h"
- #include <regex>
- SqlWrite::SqlWrite() :m_Stop(false)
- {
- std::thread(std::bind(&SqlWrite::__threadFun, this)).detach();
- }
- SqlWrite::~SqlWrite()
- {
- m_Stop = true;
- }
- void SqlWrite::addSql(const std::string & sql)
- {
- std::unique_lock<std::mutex>lock(mut);
- m_SqlList.emplace_back(sql);
- con.notify_all();
- }
- void SqlWrite::__threadFun()
- {
- while (!m_Stop)
- {
- if (__dealSql())
- {
- std::unique_lock<std::mutex>lock(mut);
- con.wait(lock);
- }
- }
- }
- bool SqlWrite::__dealSql()
- {
- std::string sql;
- {
- std::unique_lock<std::mutex>lock(mut);
- if (!m_SqlList.empty())
- {
- sql = std::move(m_SqlList.front());
- m_SqlList.pop_front();
- // 批量执行多个语句
- /*volatile int n = 0;
- std::list<std::string>::iterator it = m_SqlList.begin();
- while (it!= m_SqlList.end())
- {
- sql = sql + (*it);
- sql.append(";");
- it = m_SqlList.erase(it);
- ++n;
- if (n >=20)
- break;
- }*/
- }
- }
- // 执行sql
- if (!sql.empty())
- {
- /*std::regex reg("'");
- sql = std::regex_replace(sql, reg, "\\'");
- sql = "call save_sqls('" + sql + "')";*/
- /*LOG_DEBUG_S(sql);*/
- /*std::string mark = sql.substr(sql.length() - 1, 1);
- if (mark == ";")
- sql = sql.substr(0, sql.length() - 1);*/
- JdbcHelper::GetInstance()->jdbc_executeUpdate(sql, [](sql::PreparedStatement* stmt) {
- }, [sql](sql::SQLException &e) {
- std::cerr << "exception, SQL: " << sql << std::endl;
- Format fmt("Sql执行失败,错误信息:[%s],Sql[%s]");
- fmt % e.what() % sql;
- LOG_ERROR(fmt.str().c_str());
- });
- }
-
- return m_SqlList.empty();
- }
- SqlWrite SqlWrite::instance;
|