C/C++操作SQLite

最近幾天在學習sqlite3,頗有點收穫,下面介紹一下簡單用法:
1.先下載sqlite3.h和sqlite3.c(如果不知道怎麼下載的話就去www.sqlite.org)
如果要編譯成lib。則需要用到sqlite3.def 文件。具體要把sqlite3.def放到我們vs安裝目錄的的bin目錄下。利用lib.exe來生成 sqlite3.lib。命令爲: LIB /DEF:sqlite3.def /machine:IX86。如果執行成功的話,在bin目錄下就可以找到sqlite3.lib 和sqlite3.exp 文件。lib文件就可以用了。
我用的vs2010,所以就拿vs2010來舉例吧,新建工程SqliteTest,建好後把sqlite3.h和sqlite3.c添加到工程裏,然後在建立一個main.cpp來寫測試代碼,如圖所示:
C/C++操作SQLite - 快樂男孩 - 快樂男孩的博客
2.先介紹基本函數:
1)打開數據庫:
int sqlite3_open( const char *filename,     /* Database filename (UTF-8) */
                            sqlite3 **ppDb                /* OUT: SQLite db handle */ 
                          );
說明:filename是要打開或創建的數據庫文件,可以以.db的結尾(如:test.db),如果沒有此文件則系統會創建此文件,否則系統將打開指定的數據庫;ppDb是指針的指針,指向sqlite3*的輸出參數,因此打開數據庫前先要定義sqlite3*數據類型。
注意:sqlite3* 數據類型在以後得操作中經常被使用到。
返回類型:當返回SQLITE_OK時代表執行成功,SQLITE_OK是sqlite預定義的一個宏,在sqlite3.h中可以找到更多的宏,如打開一個test.db的操作:
sqlite3 *db = NULL;
int result ;
result = sqlite3_open("D:\\test.db", &db );
if(result == SQLITE_OK)
{
        //執行下一步操作。。。。。。。
}

2)執行有回調函數sql語句:
int sqlite3_exec(
                 sqlite3 *db,         /* An open database */
                 const char *sql,     /* SQL to be evaluated */
                 int (*callback)(void*,int,char**,char**),  /* Callback function */
                 void *,              /* 1st argument to callback */
                 char **errmsg        /* Error msg written here */
                 );
說明:第一個參數不說了(就是sqlite3_open()的那個輸出參數), 第二個參數是要執行的sql語句,以‘\0’結尾的字符竄,
第三個參數callback爲回調函數,此函數的作用是當執行完sqlite3_exec()時,自動執行的,就像windows下的線程函數一樣,
第四個參數爲傳遞給callback函數的第一個參數,最後一個爲輸出參數,執行前需要預先設置爲空,當此函數執行失敗是可以查看
errmsg來查找錯誤原因。當執行select語句時經常用到回調函數。當不需要執行回調函數時,callback參數,和void*參數都
可以設置爲空。同樣當返回SQLITE_OK時代表成功。

回調函數callback:
int (*callback)(void *para, int nCols, char **ColValue, char **ColName);
說明:para參數通過傳進來的參數,進行強制轉換來使用,
      nCols參數爲執行的結果的列數(字段數目);
      ColValue參數爲每一列的值,
      ColName參數爲字段名。
注意:ColValue和ColName都爲一維數組,通過循環來取值(利用 ColValue[i] 或者 *(ColValue + i) 可以取得到值 )。
      並不是每次回調函數都要執行,比如select語句,只有查找到結果時才執行callback函數,查找不到結構是不會執行的


3)執行無回調函數的sql語句:
int sqlite3_get_table(
  sqlite3 *db,          /* An open database */
  const char *sql,     /* SQL to be evaluated */
  char ***azResult,    /* Results of the query */
  int *nRow,           /* Number of result rows written here */
  int *nColumn,        /* Number of result columns written here */
  char **errMsg       /* Error msg written here */
);
說明:參數db不用說了
      參數sql也不用說
      參數azResult爲結果,是輸出參數。要記住它是一維數組哦,此結果中包括了表頭(即列名)從0到nColumn,azResult[i]爲列名,此後全爲
列的值,看下圖可以說明問題(此圖是粘貼的,將就看吧,可以說明問題的):

C/C++操作SQLite - 快樂男孩 - 快樂男孩的博客
        參數nRow爲結果的行數(即多少條記錄),爲輸出參數
        參數nColumn爲結果的列數(字段數),爲輸出參數
        參數errMsg是錯誤信息,前面有介紹,不多說,爲輸出參數

 

 執行完以後別忘了執行釋放資源函數:void sqlite3_free_table(char **result);

4)最後關閉數據庫:
  void sqlite_close(sqlite *db);
說明:操作完數據庫後別忘了關閉數據庫;

下面來粘貼代碼部分:
#include"sqlite3.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int MyCallback(void *para, int nColumn, char ** colValue, char ** colName);//回調函數

void main(int argc, char *argv[])
{
	sqlite3* db = NULL;
	int result = sqlite3_open("D:\\test.db", &db);

	if(result != SQLITE_OK)
	{
		printf("open database text.db failed \n");
		return;
	}
	else
	{
		printf("open database text.db success \n");
	}
	////////開始執行sqlite
	const char *sql = "create table Student(t_id integer primary key autoincrement, t_name varchar(15), t_age integer)";
	char *errMsg = NULL;
	result = sqlite3_exec(db,
		              sql,
			      NULL,
			      NULL,
			      &errMsg);
	if(result != SQLITE_OK)
	{
		printf("create table Student failed\n");
		printf("error conde %d \t error message:%s", result, errMsg);
	}
	//插入數據
	errMsg = NULL;
	sql = "insert into Student(t_name, t_age) values ('dwb', 23)";
	result = sqlite3_exec(db,
		              sq,
                              NULL,
                              NULL,
			      &errMsg);
	printf("insert message1:%s \n", errMsg);

	errMsg = NULL;
	sql = "insert into Student(t_name, t_age) values ('dhx', 25)";
	result = sqlite3_exec(db,
		              sql,
			      NULL,
			      NULL,
			      &errMsg);
	printf("insert message2:%s \n", errMsg);

	errMsg = NULL;
	sql = "insert into Student(t_name, t_age) values ('dwz', 21)";
	result = sqlite3_exec(db,
		              sql,
			      NULL,
			      NULL,
			      &errMsg);
	printf("insert message3:%s \n", errMsg);

	////////////////////////////////////////////////////////
	errMsg = NULL;
	sql = "select * from Student;";
	result = sqlite3_exec(db, sql, MyCallback, NULL, &errMsg);
	printf("select message:%s \n", errMsg);

	//執行不用回調函數的sql語句,先要設置函數所需的參數
	printf("\nUSEING sqlite3_get_table()----------------------------\n");
	sql = "select * from Student;";

	int nCols;
	int nRows;
	char **azResult;
	errMsg = NULL;
	int index = 0;

	result = sqlite3_get_table(db,sql, &azResult, &nRows, &nCols, &errMsg);
	printf("result = %d \t errMsg = %s \n", result, errMsg);
	printf("rows:%d \t cols: %d \n", nRows, nCols);
	index = nCols;

	printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
	for(int i = 0; i < nRows; i ++)
	{
		for(int j = 0; j < nCols; j ++)
		{
			printf("%s::%s", azResult[j], azResult[index]);
			index ++;
			printf("\n");
		}		
	}
	printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");

	sqlite3_free_table(azResult);
	sqlite3_close(db);
}

int MyCallback(void *para, int nColumn, char ** colValue, char ** colName)
{
	printf("----------------------------------------------------\n");
	printf("包含的列數:%d\n", nColumn);
	for(int i = 0;i < nColumn; i ++)
	{
	      printf("%s :%s\n", *(colName + i), colValue[i]);//指針和數組的兩種寫法
	}
	printf("----------------------------------------------------\n");
	return 0;
}
結果如下:

C/C++操作SQLite - 快樂男孩 - 快樂男孩的博客
學會這些後基本可以使用sqlite了,當然這些只是sqlite博大精深的冰山一角,筆者還在學習中,以後會陸續更新。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章