C/C++ 通过SQLiteSDK增删改查
在C/C++中通过SQLite SDK进行增删改查操作,你需要使用SQLite的API函数。以下是一个简单的例子,展示了如何使用这些API进行基本的数据库操作。
#include <sqlite3.h>
#include <stdio.h>
int main() {
sqlite3 *db;
char *err_msg = 0;
int rc;
// 打开数据库
rc = sqlite3_open("test.db", &db);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return 1;
}
// 创建一个表
const char *create_table_sql = "CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY, name TEXT, age INTEGER);";
rc = sqlite3_exec(db, create_table_sql, 0, 0, &err_msg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
}
// 插入数据
const char *insert_sql = "INSERT INTO user (name, age) VALUES ('Alice', 30);";
rc = sqlite3_exec(db, insert_sql, 0, 0, &err_msg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
}
// 查询数据
const char *select_sql = "SELECT id, name, age FROM user;";
sqlite3_stmt *stmt;
rc = sqlite3_prepare_v2(db, select_sql, -1, &stmt, 0);
if (rc != SQLITE_OK) {
fprintf(stderr, "Failed to prepare statement: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return 1;
}
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
int id = sqlite3_column_int(stmt, 0);
const unsigned char *name = sqlite3_column_text(stmt, 1);
int age = sqlite3_column_int(stmt, 2);
printf("ID: %d, Name: %s, Age: %d\n", id, name, age);
}
sqlite3_finalize(stmt);
// 更新数据
const char *update_sql = "UPDATE user SET age = 31 WHERE name = 'Alice';";
rc = sqlite3_exec(db, update_sql, 0, 0, &err_msg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
}
// 删除数据
const char *delete_sql = "DELETE FROM user WHERE name = 'Alice';";
rc = sqlite3_exec(db, delete_sql, 0, 0, &err_msg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
}
// 关闭数据库
sqlite3_close(db);
return 0;
}
这段代码展示了如何使用SQLite的API进行基本的数据库操作,包括创建表、插入数据、查询数据、更新数据和删除数据。在实际应用中,你需要确保处理好异常和错误,并且在适当的时候关闭数据库连接。
评论已关闭