Sqlite 与 C/C++ 开发连接方法
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                为了在C/C++程序中使用SQLite,你需要安装SQLite库,然后使用其C API来进行数据库操作。以下是一个简单的例子,展示了如何在C/C++程序中使用SQLite:
- 安装SQLite库。
- 包含SQLite头文件。
- 链接SQLite库。
以下是一个简单的C程序,展示了如何打开一个SQLite数据库,执行一个查询,并处理结果:
#include <stdio.h>
#include <sqlite3.h>
 
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;
}
 
int main() {
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;
 
    rc = sqlite3_open("test.db", &db);
    if (rc) {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return 1;
    }
 
    const char *sql = "SELECT * FROM myTable;";
 
    rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }
 
    sqlite3_close(db);
    return 0;
}确保在编译时链接SQLite库,例如使用gcc:
gcc -o sqlite_example sqlite_example.c -lsqlite3这个例子中,我们打开了一个名为test.db的SQLite数据库,并执行了一个查询,myTable是预期查询的表名。sqlite3_exec函数用于执行SQL语句,并且提供了一个回调函数callback来处理查询结果。
请确保你的开发环境已经安装了SQLite3,并且在编译时链接了SQLite3库。
评论已关闭