#include "chat.h"
// 其他函数实现略...
// 初始化数据库
int init_db(sqlite3 **db) {
int ret = sqlite3_open("chat.db", db);
if (ret != SQLITE_OK) {
fprintf(stderr, "无法打开数据库: %s\n", sqlite3_errmsg(*db));
sqlite3_close(*db);
return -1;
}
char *errmsg = NULL;
const char *create_table_sql = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL);";
ret = sqlite3_exec(*db, create_table_sql, NULL, NULL, &errmsg);
if (ret != SQLITE_OK) {
fprintf(stderr, "创建表失败: %s\n", errmsg);
sqlite3_free(errmsg);
sqlite3_close(*db);
return -1;
}
return 0;
}
// 关闭数据库
void close_db(sqlite3 *db) {
sqlite3_close(db);
}
// 添加用户到数据库
int add_user_to_db(sqlite3 *db, const char *username, const char *password) {
char *errmsg = NULL;
char sql[SQL_BUF_LEN];
snprintf(sql, SQL_BUF_LEN, "INSERT INTO users (username, password) VALUES ('%s', '%s');", username, password);
int ret = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
if (ret != SQLITE_OK) {
fprintf(stderr, "添加用户失败: %s\n", errmsg);
sqlite3_free(errmsg);
return -1;
}
return 0;
}
// 用户登录验证
int login_user(sqlite3 *db, const char *username, const char *password) {
char *errmsg = NULL;
char sql[SQL_BUF_LEN];
snprintf(sql, SQL_BUF_LEN, "SELECT * FROM users WHERE username='%s' AND password='%s';", username, password);
sqlite3_stmt *stmt;
int ret = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (ret != SQLITE_OK) {
fprintf(stderr, "查询失败: %s\n", errmsg);
sqlite3_free(errmsg);
return -1;
}
ret = sqlite3_step(stmt);
if (ret == SQLITE_ROW) {
sqlite3_finalize(stmt);
return 0;
} else if (ret == SQLITE_DONE) {
fprintf(stderr, "用户名或密码错误\n");
sqlite3_finalize(stmt);
return -1;
} else {
fprintf(