#include <iostream>
#include <sqlite3.h>
// 定义数据库操作的宏
#define DB_PATH "example.db"
#define SQL_CREATE "CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY, name TEXT, age INTEGER, email TEXT)"
#define SQL_INSERT "INSERT INTO user (name, age, email) VALUES (?, ?, ?)"
#define SQL_DELETE "DELETE FROM user WHERE id = ?"
#define SQL_UPDATE "UPDATE user SET name = ?, age = ?, email = ? WHERE id = ?"
#define SQL_SELECT "SELECT id, name, age, email FROM user WHERE id = ?"
// 创建数据库表
int createTable(sqlite3* db) {
char* errMsg = nullptr;
if (sqlite3_exec(db, SQL_CREATE, nullptr, nullptr, &errMsg) != SQLITE_OK) {
std::cerr << "创建表失败: " << errMsg << std::endl;
sqlite3_free(errMsg);
return -1;
}
return 0;
}
// 插入数据
int insertData(sqlite3* db, int id, const std::string& name, int age, const std::string& email) {
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, SQL_INSERT, -1, &stmt, nullptr) == SQLITE_OK) {
sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int(stmt, 2, age);
sqlite3_bind_text(stmt, 3, email.c_str(), -1, SQLITE_TRANSIENT);
if (sqlite3_step(stmt) != SQLITE_DONE) {
std::cerr << "插入数据失败: " << sqlite3_errmsg(db) << std::endl;
sqlite3_finalize(stmt);
return -1;
}
sqlite3_finalize(stmt);
} else {
std::cerr << "准备插入语句失败: " << sqlite3_errmsg(db) << std::endl;
return -1;
}
return 0;
}
// 删除数据
int deleteData(sqlite3* db, int id) {
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, SQL_DELETE, -1, &stmt, nullptr) == SQLITE_OK) {
sqlite3_bind_int(stmt, 1, id);
if (sqlite3_step(stmt) != SQLITE_DONE) {
std::cerr << "删除数据失败: " << sqlite3_errmsg(db) << std::endl;
sqlite3_finalize(stmt);
return -1;
}
sqlite3_finalize(stmt);
} else {
std::cerr << "准备删除语句失败: " << sqlite3_errmsg(db) << std::endl;
return -1;
}
评论已关闭