SQLite/嵌入式数据库
SQLite/嵌入式數據庫
的項目要么不使用數據庫(一兩個文配置文件就可以搞定),要么就會有很多的數據,用到 postgresql,操練sqlite的還沒有。現在我有個自己的小測試例子,寫個數據庫對比的小項目例子,我就準備把數據存儲在sqlite上,第一 數據不是很大,百位級別;為桌面應用軟件,嵌入式的。sqlite 很適合。
安裝:
1> os:ubuntu。
????由于是使用代理上的網,估計沒有配置好,apt-get intall sqlite3自動安裝沒有成功,就采用了源碼安裝。
2> package from :?http://www.sqlite.org/sqlite-autoconf-3071502.tar.gz,要選擇這個autoconf的,不然就只有源碼沒有項目管理腳本(auto 工具集)
3> tar -xzvf?sqlite-autoconf-3071502.tar.gz?, cd,./configure, make , make install. 很順利的就安裝完畢
4> 運行 sqlite3. 有錯誤
?
| 1 2 3 4 | # sqlite3 SQLite header and source version mismatch 2011-11-01 00:52:41 c7c6050ef060877ebe77b41d959e9df13f8c9b5e 2013-01-09 11:53:05 c0e09560d26f0a6456be9dd3447f5311eb4f238f |
在參考了http://jianshusoft.blog.51cto.com/2380869/824575?這篇文章后,發現
遂果斷處理:mv /usr/lib/i386-linux-gnu/*sqlite3* /tmp
在運行sqlite3, cmd的管理界面出現了。
快速入門:
shell中使用命令來了解sqlite的使用,文中大部分篇幅介紹了在sqlite3交互界面中的使用,還有些直接使用sh命令交互,非常好。http://www.sqlite.org/sqlite.html
c語言使用
一較為詳細的c語言使用sqlite3的例子,測試通過。包含了如下過程,打開數據庫文件(沒有則新建),建立表(沒有則新建),插入數據,查詢輸出,關閉數據庫文件。文件雖小,卻包含整個過程,配合博主的解釋,和評論者的積極參與,可窺探sqlite使用概貌。
源碼:
| 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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | #include<stdio.h> #include<sqlite3.h> #include<stdlib.h> int main(int argc, char** args) { ????// Create an int variable for storing the return code for each call ????int retval; ????// The number of queries to be handled,size of each query and pointer ????int q_cnt = 5,q_size = 150,ind = 0; ????char **queries = malloc(sizeof(char) * q_cnt * q_size); ????// A prepered statement for fetching tables ????sqlite3_stmt *stmt; ????// Create a handle for database connection, create a pointer to sqlite3 ????sqlite3 *handle; ????// try to create the database. If it doesnt exist, it would be created ????// pass a pointer to the pointer to sqlite3, in short sqlite3** ????retval = sqlite3_open("sampledb.sqlite3",&handle); ????// If connection failed, handle returns NULL ????if(retval) ????{ ????????printf("Database connection failed\n"); ????????return -1; ????} ????printf("Connection successful\n"); ????// Create the SQL query for creating a table ????char create_table[100] = "CREATE TABLE IF NOT EXISTS users (uname TEXT PRIMARY KEY,pass TEXT NOT NULL,activated INTEGER)"; ????// Execute the query for creating the table ????retval = sqlite3_exec(handle,create_table,0,0,0); ????// Insert first row and second row ????queries[ind++] = "INSERT INTO users VALUES('manish','mani',1)"; ????retval = sqlite3_exec(handle,queries[ind-1],0,0,0); ????queries[ind++] = "INSERT INTO users VALUES('mehul','pulsar',0)"; ????retval = sqlite3_exec(handle,queries[ind-1],0,0,0); ????// select those rows from the table ????queries[ind++] = "SELECT * from users"; ????retval = sqlite3_prepare_v2(handle,queries[ind-1],-1,&stmt,0); ????if(retval) ????{ ????????printf("Selecting data from DB Failed\n"); ????????return -1; ????} ????// Read the number of rows fetched ????int cols = sqlite3_column_count(stmt); ????while(1) ????{ ????????// fetch a row's status ????????retval = sqlite3_step(stmt); ????????if(retval == SQLITE_ROW) ????????{ ????????????// SQLITE_ROW means fetched a row ????????????// sqlite3_column_text returns a const void* , typecast it to const char* ????????????for(int col=0 ; col<cols;col++) {="" const="" char="" *val="(const" char*)sqlite3_column_text(stmt,col);="" printf("%s="%s\t",sqlite3_column_name(stmt,col),val);" }="" printf("\n");="" else="" if(retval="=" sqlite_done)="" all="" rows="" finished="" printf("all="" fetched\n");="" break;="" some="" error="" encountered="" printf("some="" encountered\n");="" return="" -1;="" close="" the="" handle="" to="" free="" memory="" sqlite3_close(handle);="" 0;="" <="" pre=""> ????<p> ????????<br> ????</p> </cols;col++)></stdlib.h></sqlite3.h></stdio.h> |
編譯:?gcc basics.c -o basics -lsqlite3 -std=c99
運行:?./basics
| 1 2 3 4 | Connection successful uname = manish? pass = mani???? activated = 1 uname = mehul?? pass = pulsar?? activated = 0 All rows fetched |
| 1 2 | # ls basics? basics.c? sampledb.sqlite3 |
例子原文:http://milky.manishsinha.net/2009/03/30/sqlite-with-c/
不知道在不使用代理情況下是否能夠看到,我僅貼原文如下(不包含評論):
------------------------------------------------------
‘C’ has always been my favourite language due to simple facts that it is beautiful and low level in nature. I don’t claim that am a ‘Geek’ in this language, its just my love that pulls me towards it. Let’s have a look at the other languages usually? liked by the public – VB, Java, Perl , Python. All of them may be good in their own ways but C kicks ass. VB?? urgh… Sorry! I vow not to code in it. It’s syntax is very unusual and every Tom,Dick and Harry claims to be a champ of that language.
The biggest problem which I face in C is storing data or in short making data persistent. One way is to write the required to a file on the disk in a fixed format. This stored data can then be read and parsed as per requirement. This approach is good for small amount of data, but what about huge amount of data? You would spend a big share of your time just for structured file I/O. Finally you would land up writing a small module for this work. Why not use any such existing database software for the same? Here comes SQLite for rescue.
I have seen a lot of tutorials on the net, they are very good but none of them suited my needs. The requirement was to explain a sample code line by line. After lots of googling and tea, I managed to make it work! The code snippet which I made is able to create new database if it does not exist, create a table if it does not exist, enter two rows and then fetch those two rows and print them on the screen.?Check the code?which I have committed the code to my personal google code repository.
Let me explain the code. Sorry for not aligning it. Please?download the raw file.
#include
#include
#include
int?main(int?argc,?char** args)
{
// Create an int variable for storing the return code for each call
int?retval;
Include stdio.h, sqlite3.h and stdlib.h , stdlib.h is for malloc and sqlite3.h contains the standard function declarations needed for the required functionality.
// The number of queries to be handled,size of each query and pointer
int?q_cnt =?5,q_size =?150,ind =?0;
char?**queries = malloc(sizeof(char) * q_cnt * q_size);
q_cnt?stored the number of queries we may want to do,?q_size?stores the max size of a SQL query,?ind?is the index.
**queries?is a double array or matrix which stores the multiple queries. The total amount of storage to be allocated is?sizeof(char) * q_cnt * q_size
// A prepered statement for fetching tables
sqlite3_stmt *stmt;
// Create a handle for database connection, create a pointer to sqlite3
sqlite3 *handle;
// try to create the database. If it doesnt exist, it would be created
// pass a pointer to the pointer to sqlite3, in short sqlite3**
retval = sqlite3_open(“sampledb.sqlite3″,&handle);
// If connection failed, handle returns NULL
if(retval)
{
printf(“Database connection failed\n”);
return?-1;
}
printf(“Connection successful\n”);
We need to create a pointer to sqlite3 and sqlite3_stmt structures. sqlite3 is the structure which is to hold the database connection handle.?sqlite3_stmt?is just like a cursor to a database.
sqlite3_open?function needs the address of the sqlite3 database instance on the disk. The second parameter is the pointer to the pointer to?sqlite3?structure. One mistake which I stumbled upon was to create a?sqlite3 ** handle?and then pass it to this function. The correct way is to create a?sqlite3*?handle and then pass the pointer to it using the & operator
// Create the SQL query for creating a table
char?create_table[100] =?“CREATE TABLE IF NOT EXISTS users (uname TEXT PRIMARY KEY,pass TEXT NOT NULL,activated INTEGER)”;
// Execute the query for creating the table
retval = sqlite3_exec(handle,create_table,0,0,0);
// Insert first row and second row
queries[ind++] =?“INSERT INTO users VALUES(‘manish’,'manish’,1)”;
retval = sqlite3_exec(handle,queries[ind-1],0,0,0);
queries[ind++] =?“INSERT INTO users VALUES(‘mehul’,'pulsar’,0)”;
retval = sqlite3_exec(handle,queries[ind-1],0,0,0);
Create a table if it does not exist and then insert two rows. Note that sqlite3 does not support inserting two rows in one single query. Maybe I need to confirm this fact again, but I never worked for me ever.
// select those rows from the table
queries[ind++] =?“SELECT * from users”;
retval = sqlite3_prepare_v2(handle,queries[ind-1],-1,&stmt,0);
if(retval)
{
printf(“Selecting data from DB Failed\n”);
return?-1;
}
// Read the number of rows fetched
int?cols = sqlite3_column_count(stmt);
Create a prepared statement for fetching data from the database usingsqlite3_prepare_v2?function call. The first parameter is the database handle itself which is a?sqlite3*?pointer. The second parameter is the SQL statement which needs to be executed. The third parameter tells upto how long the second parameter to be read. Pass -1 to make it read till line terminator. Fourth statement is the pointer to pointer to prepared statement structure. Take care of the pointer concept as I told about sqlite3 structure. The fifth parameter is filled with the unused portion of the query. Have a?look at the official documentation.
sqlite3_column_count?function gets the number of columns for the result fetched.
while(1)
{
// fetch a row’s status
retval = sqlite3_step(stmt);
if(retval == SQLITE_ROW)
{
// SQLITE_ROW means fetched a row
// sqlite3_column_text returns a const void* , typecast it to const char*
for(int?col=0?; col {
const char?*val = (const char*)sqlite3_column_text(stmt,col);
printf(“%s = %s\t”,sqlite3_column_name(stmt,col),val);
}
printf(“\n”);
}
else if(retval == SQLITE_DONE)
{
// All rows finished
printf(“All rows fetched\n”);
break;
}
else
{
// Some error encountered
printf(“Some error encountered\n”);
return?-1;
}
}
We have put this code in infinite while loop as we are not sure how much rows it contains. Usually, the table returns n+1 rows, where 1 extra row is for telling that all rows have been fetched. sqlite3_step returns the status which is actually an enumeration.?Check all the results contants here. Two most used are?SQLITE_DONE,?SQLITE_ROW. The former tells that all the rows have been fetched, now the user can come out of this loop and continue. SQLITE_ROW tells that a valid row has been fetched.
// Close the handle to free memory
sqlite3_close(handle);
return?0;
}
sqlite3_close?simply closes the database connection.
Save the code in a file named, say dataman.c , compile it using the command
$ gcc dataman.c -o dataman -l sqlite –std=c99
You obviously need to have sqlite development headers installed for compiling the same. The name of the package on Ubuntu is?libsqlite3-dev
Official SQLite Documentation
參考:
總結
以上是生活随笔為你收集整理的SQLite/嵌入式数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ThinkPHP 的URL重写时遇到N
- 下一篇: 通过VB向SQL Server数据库中录