標籤:style blog http io color ar os 使用 for
SQLite是一個著名的免費資料庫(不管是商用還是私人使用都免費),已經向眾多公司如Adobe, Airbus, Apple, google, GE, Microsoft等提供了支援。
SQLite不像其它多數的SQL資料庫,它沒有一個獨立的服務進程,它是獨立的、無進程的資料庫(用起來它也像一個語言庫),它對資料的讀寫操作是直達磁碟的。
下面我們使用C語言來試用一個SQLite
1 先到http://www.sqlite.org/download.html下載你的作業系統所對應的檔案
對方C語言的操作來說,只需要源碼就可以了:
Source Code
sqlite-autoconf-3080701.tar.gz
(1.91 MiB)
一般而言我們也需要使用命令列對資料庫中的資料進行增刪改查操作,所以也下載下面的這兩個檔案:
Precompiled Binaries for Windows
sqlite-shell-win32-x86-3080701.zip
(303.20 KiB)
sqlite-dll-win32-x86-3080701.zip
(335.37 KiB)
2 在QT Creator中建立一個純C工程(我這裡名字叫做sqlite3_test),然後修改main.c為下面這樣樣子
#include <stdio.h>#include <sqlite3.h>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; if( argc!=3 ){ fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]); return(1); } rc = sqlite3_open(argv[1], &db); if( rc ){ fprintf(stderr, "Can‘t open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return(1); } rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg); if( rc!=SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } sqlite3_close(db); return 0;}
3
將sqlite-autoconf-3080701.tar.gz解壓出來,把其中的sqlite3.h拷貝出來放到Qt工程根目錄下。
將sqlite-dll-win32-x86-3080701.zip解壓出來,把其中的sqlite3.dll拷貝到Qt工程目錄下。
將sqlite-shell-win32-x86-3080701.zip解壓出來,把其中的sqlite3.ext拷貝到C:\Windows\System32下面,這樣在CMD命令列視窗下就可以直接運行sqlite3了(shell)。
開啟一個CMD視窗,然後到達你的工程根目錄下面,然後運行sqlite3開啟SQLite Shell,按下面的操作建立一個資料庫並插入資料,以便於C語言去讀取操作:
sqlite> .tablessqlite> .open test.dbsqlite> .tablessqlite> create table tbl1(one varchar(10), two smallint);sqlite> insert into tbl1 values(‘hello!‘, 10);sqlite> insert into tbl1 values(‘goodbye‘, 20);sqlite> select *from tbl1;hello!|10goodbye|20
4 設定QT工程的編譯選項
第3步把該要的檔案都拷貝到對應的目錄了,然後現在編譯還沒有辦法通過,需要一些設定。
修改sqlite3_test.pro檔案(紅色為新增的)
TEMPLATE = appCONFIG += consoleCONFIG -= app_bundleCONFIG -= qtSOURCES += main.cLIBS += sqlite3.dllinclude(deployment.pri)qtcAddDeployment()
給應用程式添加運行參數,即從命令列啟動並執行話需要執行sqlite3_test test.db "select * from tbl1"
test.db "select * from tbl1"
5 編譯運行
參考:
Command Line Shell For SQLite http://www.sqlite.org/cli.html
C-language interface to SQLite http://www.sqlite.org/c3ref/intro.html
SQL As Understood By SQLite http://www.sqlite.org/lang.html
C語言使用SQLite3資料庫