當前位置:首頁 » 數據倉庫 » c打開sqlite資料庫
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

c打開sqlite資料庫

發布時間: 2023-06-26 18:11:59

① 如何在Linux下用C語言操作資料庫sqlite3

下面我們看看怎麼在C語言中向資料庫插入數據。
好的,我們現編輯一段c代碼,取名為 insert.c
// name: insert.c
// This prog is used to test C/C++ API for sqlite3 .It is very simple,ha !
// Author : zieckey All rights reserved.
// data : 2006/11/18
#include <stdio.h>
#include <stdlib.h>
#include "sqlite3.h"
#define _DEBUG_
int main( void )
{
sqlite3 *db=NULL;
char *zErrMsg = 0;
int rc;
rc = sqlite3_open("zieckey.db", &db); //打開指定的資料庫文件,如果不存在將創建一個同名的資料庫文件
if( rc )
{
fprintf(stderr, "Can't open database: %s
", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
else printf("You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun ! ^-^
");
//創建一個表,如果該表存在,則不創建,並給出提示信息,存儲在 zErrMsg 中
char *sql = " CREATE TABLE SensorData(
ID INTEGER PRIMARY KEY,
SensorID INTEGER,
SiteNum INTEGER,
Time VARCHAR(12),
SensorParameter REAL
);" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
#ifdef _DEBUG_
printf("%s
",zErrMsg);
#endif
//插入數據
sql = "INSERT INTO "SensorData" VALUES( NULL , 1 , 1 , '200605011206', 18.9 );" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
sql = "INSERT INTO "SensorData" VALUES( NULL , 1 , 1 , '200605011306', 16.4 );" ;
sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
sqlite3_close(db); //關閉資料庫
return 0;
}

好的,將上述代碼寫入一個文件,並將其命名為 insert.c 。
解釋:
sqlite3_exec的函數原型說明如下:
int sqlite3_exec(
sqlite3*,
const char *sql,
sqlite_callback,
void *,
char **errms

g
);

編譯:
[root@localhost temp]# gcc insert.c -lsqlite3 -L/usr/local/sqlite3/lib -I/usr/local/sqlite3/include
insert.c:28:21: warning: multi-line string literals are deprecated
[root@localhost temp]#
執行
[root@localhost temp]# ./a.out
./a.out: error while loading shared libraries: libsqlite3.so.0: cannot open shared object file: No such file or directory
[root@localhost temp]#
同樣的情況,如上文處理方法:
[root@localhost temp]# export LD_LIBRARY_PATH=/usr/local/sqlite3/lib:$LD_LIBRARY_PATH
[root@localhost temp]# ./a.out
You have opened a sqlite3 database named zieckey.db successfully!
Congratulations! Have fun ! ^-^
(null)
(null)
(null)
[root@localhost temp]#
運行成功了,好了,現在我們來看看是否插入了數據
[root@localhost temp]# /usr/local/sqlite3/bin/sqlite3 zieckey.db
SQLite version 3.3.8
Enter ".help" for instructions
sqlite> select * from SensorData;
1|1|1|200605011206|18.9

2|1|1|200605011306|16.4
sqlite>

② 如何使用SQLite

SQLite3是目前最新的SQLite版本。可以從網站上下載SQLite3的源代碼(本書使用的版本是sqlite-3.6.12.tar.gz)。
解壓縮後進入sqlite-3.6.12的根目錄,首先命令「./configure」生成Makefile文件,接著運行命令「make」對源代碼進行編譯,最後運行命令「make install」安裝SQLite3。安裝完畢後,可以運行命令sqlite3查看SQLite3是否能正常運行,如下所示:
[root@localhost ~]# sqlite3
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
可以看到,SQLite3啟動後會停留在提示符sqlite>處,等待用戶輸入SQL語句。
在使用SQLite3前需要先了解下SQLite3支持的數據類型。SQLite3支持的基本數據類型主要有以下幾類:
NULL
NUMERIC
INTEGER
REAL
TEXT
SQLite3會自動把其他數據類型轉換成以上5類基本數據類型,轉換規則如下所示:
char、clob、test、varchar—> TEXT
integer—>INTEGER
real、double、float—> REAL
blob—>NULL
其餘數據類型都轉變成NUMERIC
下面通過一個實例來演示SQLite3的使用方法。
新建一個資料庫
新建資料庫test.db(使用.db後綴是為了標識資料庫文件)。在test.db中新建一個表test_table,該表具有name,、sex、age三列。SQLite3的具體操作如下所示:
[root@localhost home]# sqlite3 test.db
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table test_table(name, sex, age);
如果資料庫test.db已經存在,則命令「sqlite3 test.db」會在當前目錄下打開test.db。如果資料庫test.db不存在,則命令「sqlite3 test.db」會在當前目錄下新建資料庫test.db。為了提高效率,SQLite3並不會馬上創建test.db,而是等到第一個表創建完成後才會在物理上創建資料庫。
由於SQLite3能根據插入數據的實際類型動態改變列的類型,所以在create語句中並不要求給出列的類型。
創建索引
為了加快表的查詢速度,往往在主鍵上添加索引。如下所示的是在name列上添加索引的過程。
sqlite> create index test_index on test_table(name);
操作數據
如下所示的是在test_table中進行數據的插入、更新、刪除操作:
sqlite> insert into test_table values ('xiaoming', 'male', 20);
sqlite> insert into test_table values ('xiaohong', 'female', 18);
sqlite> select * from test_table;
xiaoming|male|20
xiaohong|female|18
sqlite> update test_table set age=19 where name = 'xiaohong';
sqlite> select * from test_table;
xiaoming|male|20
xiaohong|female|19
sqlite> delete from test_table where name = 'xiaoming';
sqlite> select * from test_table;
xiaohong|female|19
批量操作資料庫
如下所示的是在test_table中連續插入兩條記錄:
sqlite> begin;
sqlite> insert into test_table values ('xiaoxue', 'female', 18);
sqlite> insert into test_table values ('xiaoliu', 'male', 20);
sqlite> commit;
sqlite> select * from test_table;
xiaohong|female|19
xiaoxue|male|18
xiaoliu|male|20
運行命令commit後,才會把插入的數據寫入資料庫中。
資料庫的導入導出
如下所示的是把test.db導出到sql文件中:
[root@localhost home]# sqlite3 test.db ".mp" > test.sql;
test.sql文件的內容如下所示:
BEGIN TRANSACTION;
CREATE TABLE test_table(name, sex, age);
INSERT INTO "test_table" VALUES('xiaohong','female',19);
CREATE INDEX test_index on test_table(name);
COMMIT;
如下所示的是導入test.sql文件(導入前刪除原有的test.db):
[root@localhost home]# sqlite3 test.db < test.sql;
通過對test.sql文件的導入導出,可以實現資料庫文件的備份。
11.2.2 SQLite3的C介面
以上介紹的是SQLite3資料庫的命令操作方式。在實際使用中,一般都是應用程序需要對資料庫進行訪問。為此,SQLite3提供了各種編程語言的使用介面(本書介紹C語言介面)。SQLite3具有幾十個C介面,下面介紹一些常用的C介面。
sqlite_open
作用:打開SQLite3資料庫
原型:int sqlite3_open(const char *dbname, sqlite3 **db)
參數:
dbname:資料庫的名稱;
db:資料庫的句柄;
sqlite_colse
作用:關閉SQLite3資料庫
原型:int sqlite_close(sqlite3 *db)
例如:
test.c:
#include <stdio.h>
#include <sqlite3.h>

static sqlite3 *db=NULL;

int main()
{
int rc;
rc= sqlite3_open("test.db", &db);

if(rc)
{
printf("can't open database!\n");
}
else
{
printf("open database success!\n");
}

sqlite3_close(db);
return 0;
}
運行命令「gcc –o test test.c –lsqlite3」進行編譯,運行test的結果如下所示:
[root@localhost home]# open database success!
sqlite_exec
作用:執行SQL語句
原型:int sqlite3_exec(sqlite3 *db, const char *sql, int (*callback)(void*,int,char**,char**), void *, char **errmsg)
參數:
db:資料庫;
sql:SQL語句;
callback:回滾;
errmsg:錯誤信息
例如:
test.c:
#include <stdio.h>
#include <sqlite3.h>

static sqlite3 *db=NULL;
static char *errmsg=NULL;

int main()
{
int rc;

rc = sqlite3_open("test.db", &db);
rc = sqlite3_exec(db,"insert into test_table values('bao', 'male', 24)", 0, 0, &errmsg);

if(rc)
{
printf("exec fail!\n");
}
else
{
printf("exec success!\n");
}

sqlite3_close(db);
return 0;
}
編譯完成後,運行test的結果如下所示:
[root@localhost home]# ./test
exec success!
[root@localhost home]# sqlite3 test.db
SQLite version 3.6.11
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from test_table;
bao|male|24
sqlite3_get_table
作用:執行SQL查詢
原型:int sqlite3_get_table(sqlite3 *db, const char *zSql, char ***pazResult, int *pnRow, int *pnColumn, char **pzErrmsg)
參數:
db:資料庫;
zSql:SQL語句;
pazResult:查詢結果集;
pnRow:結果集的行數;
pnColumn:結果集的列數;
errmsg:錯誤信息;
sqlite3_free_table
作用:注銷結果集
原型:void sqlite3_free_table(char **result)
參數:
result:結果集;
例如:
test.c:
#include <stdio.h>
#include <sqlite3.h>

static sqlite3 *db=NULL;
static char **Result=NULL;
static char *errmsg=NULL;

int main()
{
int rc, i, j;
int nrow;
int ncolumn;

rc= sqlite3_open("test.db", &db);
rc= sqlite3_get_table(db, "select * from test_table", &Result, &nrow, &ncolumn,
&errmsg);

if(rc)
{
printf("query fail!\n");
}
else
{
printf("query success!\n");
for(i = 1; i <= nrow; i++)
{
for(j = 0; j < ncolumn; j++)
{
printf("%s | ", Result[i * ncolumn + j]);
}
printf("\n");
}
}

sqlite3_free_table(Result);
sqlite3_close(db);
return 0;
}
編譯完成後,運行test的結果如下所示:
[root@localhost home]# ./test
query success!
xiaohong | female | 19 |
xiaoxue | female | 18 |
xiaoliu | male | 20 |
bao | male | 24 |
sqlite3_prepare
作用:把SQL語句編譯成位元組碼,由後面的執行函數去執行
原型:int sqlite3_prepare(sqlite3 *db, const char *zSql, int nByte, sqlite3_stmt **stmt, const char **pTail)
參數:
db:資料庫;
zSql:SQL語句;
nByte:SQL語句的最大位元組數;
stmt:Statement句柄;
pTail:SQL語句無用部分的指針;
sqlite3_step
作用:步步執行SQL語句位元組碼
原型:int sqlite3_step (sqlite3_stmt *)
例如:
test.c:
#include <stdio.h>
#include <sqlite3.h>

static sqlite3 *db=NULL;
static sqlite3_stmt *stmt=NULL;

int main()
{
int rc, i, j;
int ncolumn;

rc= sqlite3_open("test.db", &db);
rc=sqlite3_prepare(db,"select * from test_table",-1,&stmt,0);

if(rc)
{
printf("query fail!\n");
}
else
{
printf("query success!\n");
rc=sqlite3_step(stmt);
ncolumn=sqlite3_column_count(stmt);
while(rc==SQLITE_ROW)
{
for(i=0; i<2; i++)
{
printf("%s | ", sqlite3_column_text(stmt,i));
}
printf("\n");
rc=sqlite3_step(stmt);
}
}

sqlite3_finalize(stmt);
sqlite3_close(db);
return 0;
}
編譯完成後,運行test的結果如下所示:
[root@localhost home]# ./test
query success!
xiaohong | female | 19 |
xiaoxue | female | 18 |
xiaoliu | male | 20 |
bao | male | 24 |
在程序中訪問SQLite3資料庫時,要注意C API的介面定義和數據類型是否正確,否則會得到錯誤的訪問結果。

③ 用C語言做個sqlite資料庫~

). 打開VC新建一個「Win32 Dynamic-Link Library」工程,命名為:sqlite32). 在接下來的對話框中選擇"An empty DLL project",點 FINISH->OK3). 將源碼中所有的 *.c *.h *.def 復制到工程文件夾下4). 在工程的Source File中添加你下載到的SQLite源文件中所有*.c文件,注意這里不要添加shell.c和tclsqlite.c這兩個文件。5). 將 SQLite 源文件中的 sqlite3.def 文件添加到在工程的Source File中6). 在Header File中添加你下載到的SQLite源文件中所有*.h文件,7). 開始編譯,Build(F7)一下也許到這里會遇到一個錯誤:e:\zieckey\sqlite\sqlite3\sqlite3ext.h(22) : fatal error C1083: Cannot open include file: 'sqlite3.h': No such file or directory經檢查發現,源碼中包含sqlite3.h都是以 #include <sqlite3.h> 方式包含的,這就是說編譯器在系統默認路徑中搜索,這樣當然搜索不到 sqlite3.h 這個頭文件啦,這時可以改為 #include "sqlite3.h" ,讓編譯器在工程路徑中搜索,但是如果還有其他地方也是以 #include <sqlite3.h> 方式包含的,那麼改源碼就顯得有點麻煩,好了,我們可以這樣,在菜單欄依次選擇:Tools->Options...->Directeries在下面的Directeries選項中輸入你的 sqlite3.h 的路徑,這里也就是你的工程目錄.添加好後,我們在編譯一下就好了,最後我們在工程目錄的 Debug 目錄生成了下面兩個重要文件:動態鏈接庫文件 sqlite3.dll 和引入庫文件 sqlite3.lib二. 使用動態鏈接庫下面我們來編寫個程序來測試下我們的動態鏈接庫.在VC下新建一個空的"Win32 Console Application" Win32控制台程序,工程命名為:TestSqliteOnWindows再新建一個 test.cpp 的C++語言源程序,源代碼如下:// name: test.cpp// This prog is used to test C/C++ API for sqlite3 .It is very simple,ha !// Author : zieckey// data : 2006/11/28#include <stdio.h>#include <stdlib.h>#include "sqlite3.h" #define _DEBUG_int main( void ){sqlite3 *db=NULL;char *zErrMsg = 0;int rc;rc = sqlite3_open("zieckey.db", &db); //打開指定的資料庫文件,如果不存在將創建一個同名的資料庫文件if( rc ){fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));sqlite3_close(db);return (1);}else printf("You have opened a sqlite3 database named zieckey.db successfully!\nCongratulations! Have fun ! ^-^ \n");

④ 如何在Linux下用C/C++語言操作資料庫sqlite3

1.SQLite資料庫特點(1)SQLite資料庫是開源的嵌入式資料庫,無需獨立的資料庫引擎,直接嵌入到應用程序進程中,因此,通過API,應用程序可以直接操作它。(2)事務的處理是原子的,一致的,獨立的,可持久化的(ACID),即使在系統崩潰和掉電後。(3)SQLite資料庫通過獨占性與共享鎖來實現事務的獨立處理。(4)一個單獨的跨平台的磁碟文件就能夠存儲一個資料庫。(5)能支持2TB級的數據。(6)自包含,無外部依賴性。(7)支持NULL,INTEGER,NUMERIC,REAL,TEXT和BLOG等數據類型。(8)SQLite資料庫沒有用戶帳戶的概念。資料庫的許可權僅依賴於文件系統。2.SQLite資料庫的基本操作(1)建立資料庫sqlite3data.sqlite3在當前目錄下建立了名為data.sqlite3的資料庫。(2)建立數據表createtablecall_list(idINTEGERPRIMARYKEY,typeNUMERIC,telnumNUMERIC,bttimeTEXT,tcountNUMERIC,charge_rateNUMERIC,charge_sumNUMERIC);建立了名為call_list的數據表,有7個欄位,分別為id,type,telnum,bttime,tcount,charge_sum.charge_rate.(3)向數據表中插入數據insertintocall_listvalues($num,1,2,'new',4,5,6);(4)查詢數據表中的數據select*fromcall_list;(5)修改call_list表中的數據updatecall_listsetid=00001000whereid=10001;(6)刪除表中的數據記錄deletefromcall_listwhereid=1000;(7)SQlite中的其它常用命令.tables-列出所有的資料庫中的數據表.schematablename-列出指定數據表的結構.quit-離開資料庫(8)SQLite資料庫的導入與導出a.將data.sqlite資料庫的數據全部導出:sqlite3data.sqlite>.outputdd.sql>.mp這樣,數據就保存在dd.sql的文件中,注意這個文件不是資料庫,而是SQL語句。然後再把這些數據導入到另外一個資料庫data1.sqlite資料庫中。sqlite3data1.sqlite>.readdd.sql這樣,數據就從data.sqlite資料庫復制到data1.sqlite資料庫中去了。b.將數據表中的數據導出到a.txt中去.outputa.txt//輸出重定向到a.txtselect*fromcall_list;c.將導出的表中的數據導入到另一個資料庫的新建的表中去如:當從data.sqlite中的call_list表中導出了數據,再導入到另外一個資料庫表call中去。首先建立表call.然後.importa.txtcall即可。3.C語言操作Sqlite資料庫API:intsqlite3_open(constchar*filename,sqlite3**ppdb);第一個參數用來指定資料庫文件名。第二個參數是一個資料庫標識符指針。如果打開資料庫成功,則返回0,否則返回一個錯誤代碼。intsqlite3_close(sqlite3*);傳遞的參數是資料庫標識符指針用來關閉資料庫,操作成功是返回0,否則返回一個錯誤代碼。intsqlite3_errcode(sqlite3*db);constchar*sqlite3_errmsg(sqlite3*db);constchar*sqlite3_errmsg16(sqlite3*db);這三個函數都是返回錯誤信息,第一個函數返回的是最近調用資料庫介面的錯誤代碼,第二,第三個函數是返回最近調用資料庫介面的錯誤信息。第二個函數返回的錯誤信息是用UTF-8編碼的,第三個函數返回的錯誤信息是用UTF-16編碼的。intsqlite3_exec(sqlite3*,constchar*sql,int(*callback)(void*,int,char**,char**),void*,**errmsg);這個函數非常重用,是用來執行SQLite資料庫的SQL語句的。第一個參數是sqlite資料庫標識符指針。第二個參數是要執行的SQL語句。第三個參數是一個回調函數,在執行查詢操作時用到,其它的操作可以傳空值即NULL。第四個參數是傳遞給回調函數第一個參數的實參。第五個參數是一個錯誤信息。回調函數:intcallback(void*,intargc,char**argv,char**cname);第一個參數是從sqlite3_exec傳遞過來的參數,可以為任意的類型。第二個參數是查詢的列數。第三個參數是查詢結果集的值。第四個參數是列名。intsqlite3_get_table(sqlite3*db,constchar*sql,char***result,int*row,int*col,char**errmsg);這個函數主要是用來查詢的。第一個參數是資料庫描述符指針第二個參數是SQL語句。第三個參數是查詢的結果集。第四個參數是結果集中的行數。第五個參數是結果集中的列數。第六個參數是錯誤信息。它查詢出的行數是從欄位名開始的。即第0行是欄位名。實例:/**本例主要實現用Sqlite的回調函數進行查詢intsqlite3_exec(sqlite3*,constchar*sql,int(*callback)(void*,int,char**,char**),void*,errmsg);第一個參數是資料庫標識符第二個參數是要執行的sql命令第三個參數是回調函數第四個參數是回調函數的第一個參數第五個參數是用於指示錯誤信息其中回調函數的形式:int_sql_callback(void*arg,intargc,char**argv,char**cname);第二個參數指示結果集中的列數第三個參數是保存結果集的字元串第四個參數是結果集中的列名**/#include#include#include#include#include#includeint_call_back(void*arg,intargc,char**argv,char**cname);intmain(){intres;constchar*dbfile="data.sqlite1";char*errmsg=NULL;sqlite3*db;res=sqlite3_open(dbfile,&db);if(res!=0){perror("資料庫打開失敗");exit(EXIT_FAILURE);}//創建一張數據表constchar*sqlcreate="createtablecall_list(idINTEGERPRIMARYKEY,typeNUMERIC,telnumNUMERIC,bttimeTEXT,tcountNUMERIC,charge_rateNUMERIC,charge_sumNUMERIC)";res=sqlite3_exec(db,sqlcreate,NULL,NULL,&errmsg);if(res!=0){perror("建立數據表失敗");exit(EXIT_FAILURE);}//插入100000條數據intnum=0;structtimevaltv;gettimeofday(&tv,NULL);longold=tv.tv_sec;while(num<100000){constchar*sqlinsert="insertintocall_listvalues($num,1,2,'new',4,5,6)";res=sqlite3_exec(db,sqlinsert,NULL,NULL,&errmsg);//插入時不需要用到回調函數if(res!=0){perror("插入失敗");exit(EXIT_FAILURE);}num++;}gettimeofday(&tv,NULL);printf("插入100000條數據的時間為:%d秒/n",(tv.tv_sec-old));//更新constchar*sqlupdate="updatecall_listsetid=00001000whereid=10001";res=sqlite3_exec(db,sqlupdate,NULL,NULL,&errmsg);if(res!=0){perror("更新數據失敗");exit(EXIT_FAILURE);}//刪除constchar*sqldelete="deletefromcall_listwhereid=1000";res=sqlite3_exec(db,sqldelete,NULL,NULL,&errmsg);if(res!=0){perror("刪除數據失敗");exit(EXIT_FAILURE);}//查詢constchar*sqlquery="select*fromcall_list";res=sqlite3_exec(db,sqlquery,&_call_back,NULL,&errmsg);if(res!=0){printf("%s/n",errmsg);perror("執行失敗/n");exit(EXIT_FAILURE);}res=sqlite3_close(db);if(res!=0){perror("資料庫關閉失敗");exit(EXIT_FAILURE);}exit(EXIT_SUCCESS);}int_call_back(void*arg,intargc,char**argv,char**cname){inti;//二重指針可以看成指針數組for(i=0;i

⑤ 如何在Linux下用C語言操作資料庫sqlite3

#include<sqlite3.h>
int main(void)
{
sqlite3 *db;

char buf[1024]={0};

if(sqlite3_open("資料庫的路徑",&db)

{
printf("資料庫打開失敗\n");

return -1;
}
sprintf(buf,"select * from 表格名稱");

if(sqlite3_exec(db,buf,0,0,0)!=SQLITE_OK)

{
printf("執行失敗\n");

return -1;

}
sqlite3_close(db);

return 0;

}
上面這些只是個大體的操作