通过C实现sqlite3操作,(增删改查),导入电子词典
以下是使用C语言和SQLite3实现简单的增删改查操作,以及导入电子词典数据的示例代码。
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
// 创建或打开数据库
int open_database(sqlite3** db) {
int rc = sqlite3_open("dictionary.db", db);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(*db));
sqlite3_close(*db);
return 0;
}
return 1;
}
// 创建词条表
int create_table(sqlite3* db) {
char *err_msg = 0;
const char *create_table_sql = "CREATE TABLE IF NOT EXISTS words ("
"id INTEGER PRIMARY KEY,"
"word TEXT,"
"definition TEXT,"
"example TEXT,"
"FOREIGN KEY(id) REFERENCES definitions(id)"
");";
int rc = sqlite3_exec(db, create_table_sql, NULL, NULL, &err_msg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
return 0;
}
return 1;
}
// 插入词条
int insert_word(sqlite3* db, const char* word, const char* definition, const char* example) {
sqlite3_stmt* stmt;
const char *insert_sql = "INSERT INTO words (word, definition, example) VALUES (?, ?, ?);";
int rc = sqlite3_prepare_v2(db, insert_sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
fprintf(stderr, "Failed to prepare statement: %s\n", sqlite3_errmsg(db));
return 0;
}
sqlite3_bind_text(stmt, 1, word, -1, NULL);
sqlite3_bind_text(stmt, 2, definition, -1, NULL);
sqlite3_bind_text(stmt, 3, example, -1, NULL);
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE) {
fprintf(stderr, "Failed to execute statement: %s\n", sqlite3_errmsg(db));
sqlite3_finalize(stmt);
return 0;
}
sqlite3_finalize(stmt);
return 1;
}
// 查询词条
int query_word(sqlite3* db, const char* word) {
sqlite3_stmt* stmt;
const char *select_sql = "SELECT word, definition, example FROM words WHERE word = ?;";
int rc = sqlite3_prepare_v2(db, select_sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
fprintf(stderr, "Failed to prepare statement: %s\n", sqlite3_errmsg(db));
return 0;
}
sqlite3_bind_text(stmt, 1, word, -1, NULL);
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
cons
评论已关闭