From 27bbb5eb8482e62f056dd86a91626c5e00ac13d2 Mon Sep 17 00:00:00 2001 From: GoldBro233 Date: Tue, 22 Apr 2025 18:57:48 +0800 Subject: [PATCH] Fix bugs: Logically Fail to Login in when table is empty --- main.cpp | 3 +++ userAuth.cpp | 27 +++++++++++++++++++++++++++ userAuth.h | 2 ++ 3 files changed, 32 insertions(+) diff --git a/main.cpp b/main.cpp index e671e4e..bab026f 100644 --- a/main.cpp +++ b/main.cpp @@ -24,6 +24,9 @@ int main() { sqlite3 *db = create_connection(); init_pa_data(db); init_user_data(db); + if (is_user_table_empty(db)) { + handle_add_user_record(db); + } string login_username; string login_password; bool user_authorized = false; diff --git a/userAuth.cpp b/userAuth.cpp index 045442c..3ddcaed 100644 --- a/userAuth.cpp +++ b/userAuth.cpp @@ -1,5 +1,6 @@ #include "userAuth.h" #include "tools.h" +#include const char *CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS user_data (" "id INTEGER PRIMARY KEY AUTOINCREMENT," @@ -33,6 +34,32 @@ void init_user_data(sqlite3 *db) { }; }; +bool is_user_table_empty(sqlite3 *db) { + const char *query = "SELECT COUNT(*) FROM user_data;"; + sqlite3_stmt *stmt; + bool isEmpty = true; + + // 准备SQL语句 + if (sqlite3_prepare_v2(db, query, -1, &stmt, nullptr) != SQLITE_OK) { + std::cerr << "Failed to prepare statement: " << sqlite3_errmsg(db) + << std::endl; + return true; // 假设出错时表为空(根据你的需求可能需要调整) + } + + // 执行查询 + if (sqlite3_step(stmt) == SQLITE_ROW) { + int count = sqlite3_column_int(stmt, 0); + isEmpty = (count == 0); + } else { + std::cerr << "Failed to execute query: " << sqlite3_errmsg(db) << std::endl; + } + + // 释放语句 + sqlite3_finalize(stmt); + + return isEmpty; +} + void register_user(sqlite3 *db, const string &username, const string &userpassword) { sqlite3_stmt *stmt; diff --git a/userAuth.h b/userAuth.h index c85b802..be1407e 100644 --- a/userAuth.h +++ b/userAuth.h @@ -15,6 +15,8 @@ struct UserStruct { void init_user_data(sqlite3 *db); +bool is_user_table_empty(sqlite3 *db); + void register_user(sqlite3 *db, const string &username, const string &userpassword); bool login_user(sqlite3 *db, const std::string &username,