基於sqlite3資料庫的C、C++開發-簡單

來源:互聯網
上載者:User

基於sqlite3資料庫的C、C++開發-簡單

Sqlite3是檔案資料庫,建立資料庫後將在本地產生.db為尾碼的資料庫檔案,本人使用SQLite Maestro.exe
工具產生資料庫檔案,此工具使用方法簡單,詳細請百度。

此資料庫的源碼可以從官方網站直接下載使用:sqlite3.c  sqlite3.h,本文直接將源碼添加在我們的工程當中。

首先引入標頭檔#include "sqlite3.h"

int main()

{

     sqlite3 *db = NULL;//聲明資料庫物件

     int res = sqlite3_open(“test.db”,&db);   //開啟資料庫,第一個參數為資料庫檔案的路徑,如果不存在建立

     if (res != SQLITE_OK) {

         printf("Open db failed.\n");

         return -1;

    }

    {

        char **dbResult; //用於儲存查詢結果

        int  nRow,nColumn;//行數,列數

        char *errmsg=NULL;//錯誤資訊

        int  index;

        char sql[256]={0}; //sql語句

        int  i;

        snprintf(sql,sizeof(sql),"%s","select id,name from t1");//假設資料庫中已存在表t1

        printf("sql=%s\n",sql);

        res = sqlite3_get_table(db,sql,&dbResult,&nRow,&nColumn,&errmsg);

        if (res != SQLITE_OK) {

            printf("select failed.\n");

            printf("res=%d,errmsg=%s.\n",res,errmsg);

            sqlite3_free(errmsg);//釋放記憶體

            sqlite3_close(&db);//關閉資料庫

            return -1;

        }

        sqlite3_free(errmsg);//釋放記憶體

        printf("nRow=%d,nColumn=%d\n",nRow,nColumn);

        index = nColumn; //跳過表頭 index=0;不跳過表頭

        //輸出內容

        for(i=0;i<nRow;i++) {

            printf("id=%d,name=%s\n",atoi(dbResult[index]),dbResult[index+1]);

            index += nColumn;

        }

        sqlite3_free_table(dbResult); //釋放空間

    }

    sqlite3_close(&db);//關閉資料庫

    return 0;

此例僅僅是開啟資料庫,取出內容,輸出內容,關閉資料庫等操作

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.