一、SQLite SQLite,是一款輕型的資料庫,是遵守ACID的關聯式資料庫管理系統,它的設計目標是嵌入式的,而且目前已經在很多嵌入式產品中使用了它,它佔用資源非常的低,在嵌入式裝置中,可能只需要幾百K的記憶體就夠了。它能夠支援Windows/Linux/Unix等等主流的作業系統,同時能夠跟很多程式語言相結合,還有ODBC介面,同樣比起Mysql、PostgreSQL這兩款開源世界著名的資料庫管理系統來講,它的處理速度比他們都快。SQLite也被用於很多軟體,開啟飛信的安裝目錄,就能看見 SQLite ,估計是被用來儲存聊天記錄的。
二、下載SQLite 我下的版本為sqlite-amalgamation-3071400.zip,這個包含了主要的原始碼。sqlite-dll-win32-x86-3071400.zip這個是Windows下的編譯好的DLL檔案和def檔案,解壓縮後包含兩個檔案,sqlite3.def和sqlite3.dll。 編譯原始碼很簡單,建立立一個C++空項目,把sqlite-amalgamation-3071400.zip解壓縮後的檔案拷進去,編譯、連結,就行了。我的目的是把sqlite資料庫作為自己項目中的一部分,是作為嵌入的一部分使用的。這個要利用到sqlite3.dll檔案。可是源檔案只有sqlite3.def和sqlite3.dll沒有sqlite3.lib檔案,怎麼用呢?根據def檔案可以產生對應的LIB檔案。以下是命令列產生LIB檔案。找到VS的安裝路徑,我的是D:\ProgramFiles\,用命令列進入以下路徑。
D:\Program Files\Microsoft Visual Studio 9.0\VC\bin>lib /def:sqlite3.def /machine:ix86
三、使用
1 //#pragma comment(lib,"sqlite3.lib") 2 #include <iostream> 3 #include <string> 4 #include <sstream> 5 #include "sqlite3.h" 6 7 using namespace std; 8 9 sqlite3* pDB; 10 static int callback(void *NotUsed, int argc, char **argv, char **azColName) 11 { 12 int i =0; 13 std::cout<< azColName[i] << " = "<< (argv[i] ? argv[i] : "NULL")<< ", " ; 14 std::cout<< "\n"; 15 return 0; 16 } 17 int main() 18 { 19 int res = sqlite3_open("mydatabase.db", &pDB); 20 if( res ){ 21 std::cout << "Can't open database: "<< sqlite3_errmsg(pDB); 22 sqlite3_close(pDB); 23 return -1; 24 } 25 char* errMsg; 26 string dropTab="drop table test;"; 27 string createStrSQL= "create table test(one int, two long);"; 28 int res; 29 res = sqlite3_exec(pDB,dropTab.c_str(),0,0, &errMsg); 30 if (res != SQLITE_OK) 31 { 32 std::cout << "執行SQL出錯." << errMsg << std::endl; 33 return -1; 34 } 35 res = sqlite3_exec(pDB,createStrSQL.c_str(),0,0, &errMsg); 36 if (res != SQLITE_OK) 37 { 38 std::cout << "執行建立table的SQL出錯." << errMsg << std::endl; 39 return -1; 40 } 41 else 42 std::cout << "建立table的SQL成功執行."<< std::endl; 43 44 for (int i= 1; i < 10; ++i) 45 { 46 stringstream strsql; 47 strsql << "insert into test values("; 48 strsql << i << ","<< (i+10) << ");"; 49 std::string str = strsql.str(); 50 res = sqlite3_exec(pDB,str.c_str(),0,0, &errMsg); 51 if (res != SQLITE_OK) 52 { 53 std::cout << "執行SQL出錯." << errMsg << std::endl; 54 return -1; 55 } 56 } 57 string strSQL= "select * from test;"; 58 int res = sqlite3_exec(pDB,strSQL.c_str(),callback,0, &errMsg); 59 if (res != SQLITE_OK) 60 { 61 std::cout << "執行SQL出錯." << errMsg << std::endl; 62 return -1; 63 } 64 else 65 std::cout << "SQL成功執行."<< std::endl; 66 return 0; 67 }