最近在準備 SQLite 相關的 paper presentation,突然被一句話給吸引了
SQLite is a C-language library
Include SQLite lib就能直接操作Database了?為了更了解這句話的意思,我花了點時間試了一下,試完真的懂了為什麼官方說他們的競爭對手不是MySQL,而是"fopen()"
我先從官網(https://www.sqlite.org/download.html)下載source code
選擇最新版的sqlite-amalgamation-*.zip,並解壓縮,如下
在該資料夾中新增一個檔案demo.c (網路上看到的範例)
#include <stdio.h>#include "sqlite3.h"
int main(int argc, char *argv[]){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));return (0);}else{fprintf(stderr, "Opened database successfully\n");}sqlite3_close(db);}
編譯並執行後(gcc demo.c sqlite3.c -o demo && demo),就可以直接操作database
這邊附上官方介紹文件 An Introduction To The SQLite C/C++ Interface
可以搭配 SQLite – C/C++ | 菜鸟教程 (runoob.com) 練習
我拿上面的程式碼改了一點點
#include <stdio.h>#include "sqlite3.h"// 印出搜尋結果 (Print query result)static int callback(void *NotUsed, int argc, char **argv, char **azColName){int i;for (i = 0; i < argc; i++){printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");}printf("\n");return 0;}int main(int argc, char *argv[]){sqlite3 *db;char *zErrMsg = 0;int rc;char sql[1000];rc = sqlite3_open("test.db", &db);if (rc){fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));return (0);}else{fprintf(stderr, "Opened database successfully\n");}// 輸入 SQL 語句 (Enter SQL statement), SELECT, CREATE, DELETE ...printf("Enter SQL statement('q' to quit): ");while (gets(sql) && sql[0] != 'q'){// 執行 SQL 語句 (Execute SQL statement)rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);if (rc != SQLITE_OK){fprintf(stderr, "SQL error: %s\n", zErrMsg);sqlite3_free(zErrMsg);}printf("Enter SQL statement('q' to quit): ");}sqlite3_close(db);}
執行後可以下SQL語句來操作資料庫,真的挺簡單的
更詳細的內部解構可以參考 (636) D. Richard Hipp - SQLite [The Databaseology Lectures - CMU Fall 2015] - YouTube,這個影片講得很詳細
沒有留言:
張貼留言
注意:只有此網誌的成員可以留言。