步骤:
1. 包含SQLite头文件:
#include <sqlite3.h>
2. 打开数据库连接:
sqlite3 *db;
int rc = sqlite3_open("your_database.db", &db);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return rc;
}
3. 执行SQL语句:
const char *sql = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT);";
rc = sqlite3_exec(db, sql, 0, 0, 0);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot create table: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return rc;
}
4. 插入数据:
const char *insert_sql = "INSERT INTO users (name) VALUES ('John Doe');";
rc = sqlite3_exec(db, insert_sql, 0, 0, 0);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot insert data: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return rc;
}
5. 查询数据:
const char *select_sql = "SELECT * FROM users;";
rc = sqlite3_exec(db, select_sql, callback, 0, 0);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot select data: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return rc;
}
6. 关闭数据库连接:
sqlite3_close(db);
示例回调函数:
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
for (int i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
这只是一个简单的示例,实际中可能需要更多的错误处理和复杂的SQL语句。此外,通常在实际应用中,应该使用参数化查询,以防止SQL注入攻击。
请确保在使用SQLite的C/C++ API时查阅SQLite官方文档,以获取更详细的信息和最佳实践。
转载请注明出处:http://www.pingtaimeng.com/article/detail/9181/SQLite