SQLite的使用(包括編譯安裝的步驟)


SQLite官網
http://www.sqlite.org/

 

SQLite簡介

  SQLite是一款輕型的數據庫,是遵守ACID(原子性、一致性、隔離性和持久性)的關系式數據庫管理系統。SQLite實現了多數的SQL-92標准,包括事務、觸發器和多數的復雜查詢。
  SQLite的設計目標是嵌入式的,它占用的資源非常低,目前在很多嵌入式產品中都使用了SQLite。
  SQLite是跨平台的、可移植的,能夠支持Windows/Linux/Unix等主流操作系統,同時SQLite能夠和很多程序語言相結合,例如Tcl、C#、PHP和Java等。在C/C++程序中可以很方便的使用SQLite庫,Python自2.5版本后也內置了SQLite模塊,模塊名為sqlite3。
  SQLite第一個Alpha版本誕生於2000年5月。目前SQLite最新的版本是 3.11 。

 

SQLite的特性

  1. ACID事務
  2. 開放源代碼
  3. 小巧、獨立、簡單易用,同時功能不落后於流行的數據庫
  4. 整個數據庫存儲在一個文件中,不需要服務器支持
  5. 跨平台,支持Windows/Linux/Unix等主流操作系統
  6. 支持多種開發語言,C, C++,PHP, Perl, Java, C#,Python等
  7. 簡潔易用的API接口

 

SQLite 管理客戶端

 

安裝


(一)通過編譯源碼安裝

下載地址 https://www.sqlite.org/download.html

下載文件 sqlite-autoconf-3110000.tar.gz

復制代碼
// 解壓
tar zxvf sqlite-autoconf-3110000.tar.gz

// 安裝
cd sqlite-autoconf-3110000
./configure --prefix=/usr/local
make
make install
復制代碼

 

源碼編譯會生成這樣幾個等的文件:

/usr/bin/sqlite3

/usr/local/include/sqlit3.h

/usr/local/lib/libsqlite3.so

image

 

(二)通過包安裝SQLite

sudo apt-get install sqlite3 libsqlite3-dev

 

編譯程序的時候需要這樣

gcc dbtest.c -o dbtest –lsqlite3

注:-l和sqlite3之間可以有空格。

 

(三)不安裝SQLite編譯程序
在Linux系統上,將dbtest.c程序保存在libsqlite3.so , sqlite3和sqlite3.h同一個目錄下。
可以通過執行這條命令編譯文件:

gcc dbtest.c -o dbtest -lsqlite3 -L.

image

sqlite3二進制程序和sqlite3.h都可以在SQLite官網下載到,libsqlite3.so的獲取有兩種方法:

1)通過源碼編譯會在/usr/local/lib/目錄下生成libsqlite3.so文件,cp出來就可以了;

2)在系統/usr/lib/x86_64-linux-gnu目錄下本來就有(我是64位的系統)。

image

如果安裝了libsqlite3-dev,該目錄下會多出如下的文件:

image

 

小測試


下面就是dbtest.c的程序,只有打開和關閉的操作。

復制代碼
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

int main(void)
{
    sqlite3 *db = NULL;
    int rc;
    // 打開數據庫,不存在會創建一個新的
    rc = sqlite3_open("my.db",&db);
    if(rc)  // 不為0,打開失敗
    {
        fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db));
        sqlite3_close(db);
        exit(0);
    }
    else
    {
        printf("open db success!\n");
        sqlite3_close(db);
    }
    return 0;
}
復制代碼

 

編譯時常見的錯誤

1)沒有找到頭文件,錯誤信息包含下面這句:

sqlite3.h: 沒有那個文件或目錄

2)沒有找到庫文件,錯誤信息包含下面這些句子:

: undefined reference to `sqlite3_open'
: undefined reference to `sqlite3_errmsg'
: undefined reference to `sqlite3_close'
: undefined reference to `sqlite3_close'

 

gcc的-l、-L、-I參數

-l參數就是用來指定程序要鏈接的庫,例如本程序中要鏈接libsqlite3.so,去掉前后綴就是了。

放在/lib和/usr/lib和/usr/local/lib里的庫直接用-l參數就能鏈接了。

如果庫文件不在這3個目錄下,譬如說自己寫的庫,就需要用-L+Dir的方式指定庫文件的目錄。

-include、-I參數是用來指定頭文件目錄,gcc默認目錄是/usr/include

 

SQLite API 函數


SQLite是一個調用級別上的接口庫,它能夠嵌入到應用程序中。所有的API函數都是以sqlite3_前綴命名,並且在sqlite3.h中聲明。

序號 API & 描述
1 sqlite3_open(const char *filename, sqlite3 **ppDb)

如果 filename 參數是 NULL 或 ':memory:',那么 sqlite3_open() 將會在 RAM 中創建一個內存數據庫,這只會在 session 的有效時間內持續。

如果文件不存在,SQLite將自動的創建數據庫文件。

2 sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)

第一個參數 sqlite3 是打開的數據庫對象,sqlite_callback 是一個回調,data 作為其第一個參數,errmsg 將被返回用來獲取程序生成的任何錯誤。

sqlite3_exec() 程序解析並執行由 sql 參數所給的每個命令,直到字符串結束或者遇到錯誤為止。

3 sqlite3_close(sqlite3*)

關閉數據庫連接,並且釋放了分配給該連接的所有資源。

如果還有查詢沒有完成,sqlite3_close() 將返回 SQLITE_BUSY 禁止關閉的錯誤消息。

注:在打開或創建一個數據庫文件時,SQLite遵守一個懶惰策略:知道該文件被閱讀訪問時才真正的打開或者創建。

sql字符串可以由多個SQL語句組成,例如:

sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; " \ "SELECT * from COMPANY";

sqlite3_exec()函數如果不需要回調,最簡潔可以這樣寫:

rc = sqlite3_exec(db, sql, 0, 0, &errorMsg);
if(errorMsg)
    printf("%s\n", errorMsg);
else
    printf("success!\n");

判斷出錯的部分也可以這樣寫:

復制代碼
if( rc != SQLITE_OK )
{
    fprintf(stderr, "SQL error: %s\n", zErrMsg);
    sqlite3_free(zErrMsg);
}
else
{
    fprintf(stdout, "success!\n");
}
復制代碼

 

回調函數的原型

復制代碼
typedef int (*sqlite3_callback)(
void*,    /* Data provided in the 4th argument of sqlite3_exec() */
int,      /* The number of columns in row */
char**,   /* An array of strings representing fields in the row */
char**    /* An array of strings representing column names */
);
復制代碼

第一個參數通過sqlite3_exec的第第四個參數傳入的

第二個參數是結果行的列數

第三個參數是行中列數據的指針

第四個參數是行中列名稱的指針

如果sqlite3_exec的第三個參數回調函數指針不為空,那么它會為每個來自執行的SQL語句的結果行調用。

如果在執行sql語句中有錯誤發生,那么當前的語句的執行被停止,后續的語句也被跳過。

 

下面就是一個回調函數的具體例子:

復制代碼
static int callback(void *data, int argc, char **argv, char **ColName){
   int i;
   fprintf(stderr, "%s: ", (const char*)data);
   for(i=0; i<argc; i++){
      printf("%s = %s\n", ColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
   return 0;
}
復制代碼


sqlite3_get_table()函數

復制代碼
int sqlite3_get_table(
  sqlite3 *db,          /* An open database */
  const char *zSql,     /* SQL to be evaluated */
  char ***pazResult,    /* Results of the query */
  int *pnRow,           /* Number of result rows written here */
  int *pnColumn,        /* Number of result columns written here */
  char **pzErrmsg       /* Error msg written here */
);
// 不論數據庫查詢是否成功,都釋放 char** 查詢結果
void sqlite3_free_table(char **result);
復制代碼

第1個參數數據庫對象。
第2個參數是 sql 語句,以\0結尾的字符串。
第3個參數是查詢結果,它依然一維數組。它內存布局是:第一行是字段名稱,后面是緊接着是每個字段的值。
第4個參數是查詢出多少條記錄(多少行)。
第5個參數是多少個字段(多少列)。
第6個參數是錯誤信息。

pazResult返回的字符串數量實際上是(*pnRow+1)*(*pnColumn)

 

下面就是一個sqlite3_get_table()函數的具體例子:

復制代碼
result = sqlite3_get_table( db, “select * from table1”, &dbResult, &nRow, &nColumn, &errmsg );
if( SQLITE_OK == result )    // 查詢成功
{
    index = nColumn;
    // dbResult 第一行數據是字段名稱,從 nColumn 索引開始才是真正的數據
    printf( “查到%d條記錄\n”, nRow );

    for(  i = 0; i < nRow ; i++ )
    {
         printf( “第 %d 條記錄\n”, i+1 );
         for( j = 0 ; j < nColumn; j++ )
         {
              printf( “字段名:%s  >  字段值:%s\n”,  dbResult[j], dbResult [index] );
              ++index;
              // dbResult 的字段值是連續的,從第0索引到第 nColumn - 1索引都是字段名稱,
        // 從第 nColumn 索引開始,后面都是字段值 } printf( “--------\n” ); } } // 釋放查詢結果 sqlite3_free_table( dbResult );
復制代碼

 

還有一個例子:

復制代碼
char query(sqlite3 *db, const char *sql) {
    printf("%s\n", sql);
    char *select_str = "SELECT";
    char *errorMsg;
    char *str_str = strstr(sql, select_str);
    if(str_str) {
        printf("in it, %s\n", str_str);
        int row = 0, column = 0, i = 0;
        char **result;
        sqlite3_get_table(db, sql, &result, &row, &column, &errorMsg);
        printf("row:%d, column:%d\n", row, column);
        for(; i < column * (row + 1); i++) {
            printf("result[%d]=%s\n", i, result[i]);
        }
    }else{
        sqlite3_exec(db, sql, 0, 0, &errorMsg);
    }
    if(errorMsg){
        printf("%s\n", errorMsg);
    }else{
        printf("success!\n");
    }
}
復制代碼

 

sqlite3.h中定義的助記符常量

復制代碼
#define SQLITE_OK           0   /* Successful result */
/* beginning-of-error-codes */
#define SQLITE_ERROR        1   /* SQL error or missing database */
#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
#define SQLITE_PERM         3   /* Access permission denied */
#define SQLITE_ABORT        4   /* Callback routine requested an abort */
#define SQLITE_BUSY         5   /* The database file is locked */
#define SQLITE_LOCKED       6   /* A table in the database is locked */
#define SQLITE_NOMEM        7   /* A malloc() failed */
#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
#define SQLITE_FULL        13   /* Insertion failed because database is full */
#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
#define SQLITE_EMPTY       16   /* Database is empty */
#define SQLITE_SCHEMA      17   /* The database schema changed */
#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
#define SQLITE_MISMATCH    20   /* Data type mismatch */
#define SQLITE_MISUSE      21   /* Library used incorrectly */
#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
#define SQLITE_AUTH        23   /* Authorization denied */
#define SQLITE_FORMAT      24   /* Auxiliary database format error */
#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
#define SQLITE_NOTADB      26   /* File opened that is not a database file */
#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
/* end-of-error-codes */
復制代碼

 

其他


SQLite 教程
http://www.runoob.com/sqlite/sqlite-tutorial.html

 

常用命令學習
http://yuanzhifei89.iteye.com/blog/1123870
http://blog.csdn.net/linchunhua/article/details/7184439

 

[API]
官方中的介紹:http://www.sqlite.org/cintro.html
http://www.cnblogs.com/kfqcome/archive/2011/06/27/2136999.html
http://blog.chinaunix.net/uid-8447633-id-3321394.html

 

使用VC將sqlite3.def轉化為sqlite3.lib
http://www.letuknowit.com/topics/20120421/convert-sqlite-def-to-sqlite-lib.html/
windows系統中使用C/C++操作sqlite數據庫示例程序
http://www.letuknowit.com/topics/20120422/use-c-or-cplusplus-connect-to-sqlite-in-windows.html/

 

http://www.cnblogs.com/luoxu34/p/5235737.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM