为数据库插入增加保护
This commit is contained in:
@@ -16,6 +16,30 @@ SQLite::SQLite(const std::string& dbPath) {
|
||||
}
|
||||
}
|
||||
|
||||
bool SQLite::checkConnection() {
|
||||
if (!m_db) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 执行一个简单的查询来检查连接是否仍然有效
|
||||
const char* sql = "SELECT 1;";
|
||||
sqlite3_stmt* stmt = nullptr;
|
||||
if (sqlite3_prepare_v2(m_db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
|
||||
LOG_F(ERROR, "数据库连接检查失败: %s", sqlite3_errmsg(m_db));
|
||||
return false;
|
||||
}
|
||||
|
||||
bool success = (sqlite3_step(stmt) == SQLITE_ROW);
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
if (!success) {
|
||||
LOG_F(ERROR, "数据库连接检查失败: 查询未返回结果");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
SQLite::~SQLite()
|
||||
{
|
||||
if (m_db) sqlite3_close(m_db);
|
||||
@@ -367,10 +391,18 @@ bool SQLite::createTable()
|
||||
}
|
||||
|
||||
bool SQLite::insertData(const ccuState data) {
|
||||
std::lock_guard<std::mutex> lock(m_dbMutex);
|
||||
|
||||
if (!m_db) {
|
||||
std::cerr << "数据库未打开,无法插入数据。" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查数据库连接是否仍然有效
|
||||
if (!checkConnection()) {
|
||||
std::cerr << "数据库连接无效,无法插入数据。" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* sql = R"(
|
||||
INSERT INTO CcuState (
|
||||
@@ -840,10 +872,18 @@ bool SQLite::insertData(const disLowBusCmd cmd) {
|
||||
}
|
||||
|
||||
bool SQLite::insertData(const disHighVolBusState data) {
|
||||
std::lock_guard<std::mutex> lock(m_dbMutex);
|
||||
|
||||
if (!m_db) {
|
||||
std::cerr << "数据库未打开,无法插入数据。" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查数据库连接是否仍然有效
|
||||
if (!checkConnection()) {
|
||||
std::cerr << "数据库连接无效,无法插入数据。" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* sql = R"(
|
||||
INSERT INTO disHighVolBusState (
|
||||
@@ -945,10 +985,18 @@ bool SQLite::insertData(const disHighVolBusState data) {
|
||||
}
|
||||
|
||||
bool SQLite::insertData(const disHighAVolBusState data) {
|
||||
std::lock_guard<std::mutex> lock(m_dbMutex);
|
||||
|
||||
if (!m_db) {
|
||||
std::cerr << "数据库未打开,无法插入数据。" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查数据库连接是否仍然有效
|
||||
if (!checkConnection()) {
|
||||
std::cerr << "数据库连接无效,无法插入数据。" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* sql = R"(
|
||||
INSERT INTO disHighAVolBusState (
|
||||
|
||||
Reference in New Issue
Block a user