sqlite3 C接口基础
函數(shù)聲明如下:
int sqlite3_open(const char *filename, /* Database filename (UTF-8) */sqlite3 **ppDb /* OUT: SQLite db handle */ );int sqlite3_exec(sqlite3*, /* An open database */const char *sql, /* SQL to be evaluated */int (*callback)(void*,int,char**,char**), /* Callback function */void *, /* 1st argument to callback */char **errmsg /* Error msg written here */ );int sqlite3_close(sqlite3*);?
簡單來說就是:
sqlite3_open() //打開(創(chuàng)建)一個數(shù)據(jù)庫
sqlite3_exec() //執(zhí)行一條SQL語句
sqlite3_close() //關閉數(shù)據(jù)庫
?
注意:
程序編譯之前需要 sudo apt-get install libsqlite3-dev
程序編譯 gcc demo.c -lsqlite3
示例程序:
#include <stdio.h> #include <stdlib.h> #include <sqlite3.h>static int callback(void *data, int argc, char *argv[], char *azColName[]) {int i;fprintf(stderr, "%s: ", (const char *)data);for (i = 0; i < argc; i++) {fprintf(stdout, "%s = %s\n", azColName[i], argv[i]?argv[i]:"NULL");}fprintf(stdout, "\n");return 0; }int main(int argc, char *argv[]) {int ret;sqlite3 *db;char *sql = NULL;char *zErrMsg = NULL;const char *data = "CallBack function called";ret = sqlite3_open("testDB.db", &db);if (ret) {fprintf(stderr, "Can't open database: %s", sqlite3_errmsg(db));exit(0);} else {fprintf(stdout, "Opened database successfully\n");} #if 0sql = "DELETE from COMPANY where ID=2;"\"SELECT * from COMPANY;"; #elsesql = "DELETE from COMPANY where ID=3;"; #endifret = sqlite3_exec(db, sql, callback, (void *)data, &zErrMsg);if (ret != SQLITE_OK) {fprintf(stderr, "SQL error %s\n", zErrMsg);sqlite3_free(zErrMsg);} else {fprintf(stdout, "Operation done successfully\n");}sqlite3_close(db);return 0; }?
重要:
1.回調函數(shù)作用就是接受、處理數(shù)據(jù)庫查詢的數(shù)據(jù),其中參數(shù)的意義分別為:
1>data 用戶自己傳入
2>argc 查詢到的該條數(shù)據(jù)一共有幾列
3>argv 獲取到的該列的數(shù)據(jù)
4>azColName 列名稱
2.sqlite3_exec執(zhí)行之后如果出錯,則需要釋放?zErrMsg。
參考資料:
https://www.sqlite.org/index.html(sqlite官方文檔)
https://www.runoob.com/sqlite/sqlite-tutorial.html(菜鳥教程sqlite)
https://cloud.tencent.com/developer/doc/1228(騰訊云sqlite開發(fā)者手冊)
http://www.cnblogs.com/mingforyou/archive/2013/02/19/2917122.html
轉載于:https://www.cnblogs.com/rivsidn/p/10818664.html
總結
以上是生活随笔為你收集整理的sqlite3 C接口基础的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS 修改navigationCont
- 下一篇: SpringBoot集成Redis实现排