自製的一個操作sqlite資料庫的庫檔案,寫時用的IDE是KDevelop3.3.4。
標頭檔:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#ifndef _SQLITE3LIB_H_ #define _SQLITE3LIB_H_ #include <stdio.h> #include <stdlib.h> #include<sqlite3.h> typedef struct { char **result; int row; int col; char *errmsg; }sqliteResSet; /* *功能:執行sql語句,調用成功時,返回0,並釋放errmsg,適用於執行“增刪改”類型的sql語句 *db:要進行操作的資料庫,不需要先開啟 *errmsg:執行sql語句時如果發生錯誤所返回的資訊 */ int sqlite3_carrySql(const char *db, const char *sql, char *errmsg); /* *功能:執行查詢的sql語句,查詢成功時,返回0,並將一個結果集儲存到table中 *db:要進行操作的資料庫,不需要先開啟 */ int sqlite3_getResSet(const char *db, const char *sql, sqliteResSet *table); #endif /*_SQLITE3LIB_H_*/ |
啟動並執行demo:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <stdio.h> #include <stdlib.h> #include<sqlite3Lib.h> int main(int argc, char *argv[]) { sqliteResSet table; int result, i, j; char *Errormsg; char *sql="create table table1(id, name);insert into table1 values(1, 'Tom');insert into table1 values(2, 'Tom')"; result = sqlite3_carrySql("test.db", sql, Errormsg); if(result) { printf("操作資料庫失敗!n"); } sql = "select * from table1"; result = sqlite3_getResSet("test.db", sql, &table); if(result) { printf("查詢資料庫失敗!n"); } else { printf("列印table1的全部資料:n"); /*sqlite資料庫的表的資料相當於存放在一個一維數組裡面,且第一行為表的列名*/ for(i = 0; i < table.row + 1; i++) { for(j = 0; j < table.col; j++) { printf("%st", table.result[j + i * table.col]); } printf("n"); } } return EXIT_SUCCESS; |