diff --git a/hikyuu_cpp/hikyuu/utilities/db_connect/mysql/MySQLStatement.cpp b/hikyuu_cpp/hikyuu/utilities/db_connect/mysql/MySQLStatement.cpp index f82ceee9..8a38a42c 100755 --- a/hikyuu_cpp/hikyuu/utilities/db_connect/mysql/MySQLStatement.cpp +++ b/hikyuu_cpp/hikyuu/utilities/db_connect/mysql/MySQLStatement.cpp @@ -30,15 +30,15 @@ MySQLStatement::MySQLStatement(DBConnectBase* driver, const std::string& sql_sta m_meta_result(nullptr), m_needs_reset(false), m_has_bind_result(false) { - m_stmt = mysql_stmt_init(m_db); - HKU_CHECK(m_stmt != nullptr, "Failed mysql_stmt_init!"); - int ret = mysql_stmt_prepare(m_stmt, sql_statement.c_str(), sql_statement.size()); - if (ret != 0) { - std::string stmt_errorstr(mysql_stmt_error(m_stmt)); - mysql_stmt_close(m_stmt); - m_stmt = nullptr; - SQL_THROW(ret, "Failed prepare sql statement: {}! error msg: {}!", sql_statement, - stmt_errorstr); + if (!_prepare()) { + // 尝试重连 + if ((dynamic_cast(driver))->ping()) { + m_db = (dynamic_cast(driver))->m_mysql; + HKU_CHECK(_prepare(), "Failed prepare statement, while reconnect to mysql!"); + HKU_INFO("success reconnect to mysql"); + } else { + HKU_THROW("Failed reconnect mysql!"); + } } auto param_count = mysql_stmt_param_count(m_stmt); @@ -65,6 +65,21 @@ MySQLStatement::~MySQLStatement() { mysql_stmt_close(m_stmt); } +bool MySQLStatement::_prepare() { + m_stmt = mysql_stmt_init(m_db); + HKU_ERROR_IF_RETURN(!m_stmt, false, "Failed mysql_stmt_init!"); + + int ret = mysql_stmt_prepare(m_stmt, m_sql_string.c_str(), m_sql_string.size()); + if (ret != 0) { + std::string stmt_errorstr(mysql_stmt_error(m_stmt)); + mysql_stmt_close(m_stmt); + m_stmt = nullptr; + HKU_ERROR("Failed prepare sql statement: {}! error msg: {}!", m_sql_string, stmt_errorstr); + return false; + } + return true; +} + void MySQLStatement::_reset() { if (m_needs_reset) { int ret = mysql_stmt_reset(m_stmt); diff --git a/hikyuu_cpp/hikyuu/utilities/db_connect/mysql/MySQLStatement.h b/hikyuu_cpp/hikyuu/utilities/db_connect/mysql/MySQLStatement.h index 3df3a012..b3928d03 100755 --- a/hikyuu_cpp/hikyuu/utilities/db_connect/mysql/MySQLStatement.h +++ b/hikyuu_cpp/hikyuu/utilities/db_connect/mysql/MySQLStatement.h @@ -60,6 +60,7 @@ public: virtual void sub_getColumnAsBlob(int idx, std::vector &item) override; private: + bool _prepare(); void _reset(); void _bindResult();