MySQL statement 准备失败时尝试重连
Some checks failed
macOS_arm64 / build (arm64, shared, macos-14) (push) Has been cancelled
ubuntu-build / build (ubuntu-latest) (push) Has been cancelled
ubuntu-aarch64-build / build (aarch64-linux-musl, ubuntu-latest) (push) Has been cancelled
ubuntu-python-build / build (ubuntu-latest) (push) Has been cancelled
win-build / build (x64, windows-2019) (push) Has been cancelled
win-build / build (x64, windows-2022) (push) Has been cancelled
win-python-build / build (x64, windows-2019) (push) Has been cancelled
win-python-build / build (x64, windows-2022) (push) Has been cancelled

This commit is contained in:
fasiondog 2024-11-13 13:01:23 +08:00
parent cdd5c8ca4f
commit 7a9b842ada
2 changed files with 25 additions and 9 deletions

View File

@ -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<MySQLConnect*>(driver))->ping()) {
m_db = (dynamic_cast<MySQLConnect*>(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);

View File

@ -60,6 +60,7 @@ public:
virtual void sub_getColumnAsBlob(int idx, std::vector<char> &item) override;
private:
bool _prepare();
void _reset();
void _bindResult();