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. 有错误
1234# sqlite3SQLite header and source version mismatch2011-11-0100:52:41c7c6050ef060877ebe77b41d959e9df13f8c9b5e2013-01-0911:53:05c0e09560d26f0a6456be9dd3447f5311eb4f238f在参考了http://jianshusoft.blog.51cto.com/2380869/824575这篇文章后,发现
- 在make install 的log中指出安装的路径都在/usr/local 下,在configure中也有对应的代码代码指出了这个路径
- 在/usr/lib/i386-linux-gnu中也确实有libsqlite3*的文件
遂果断处理:mv /usr/lib/i386-linux-gnu/*sqlite3* /tmp
在运行sqlite3, cmd的管理界面出现了。
快速入门:
shell中使用命令来了解sqlite的使用,文中大部分篇幅介绍了在sqlite3交互界面中的使用,还有些直接使用sh命令交互,非常好。http://www.sqlite.org/sqlite.html
c语言使用
一较为详细的c语言使用sqlite3的例子,测试通过。包含了如下过程,打开数据库文件(没有则新建),建立表(没有则新建),插入数据,查询输出,关闭数据库文件。文件虽小,却包含整个过程,配合博主的解释,和评论者的积极参与,可窥探sqlite使用概貌。
源码:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869#include<stdio.h>#include<sqlite3.h>#include<stdlib.h>intmain(intargc,char** args){// Create an int variable for storing the return code for each callintretval;// The number of queries to be handled,size of each query and pointerintq_cnt = 5,q_size = 150,ind = 0;char**queries =malloc(sizeof(char) * q_cnt * q_size);// A prepered statement for fetching tablessqlite3_stmt *stmt;// Create a handle for database connection, create a pointer to sqlite3sqlite3 *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 NULLif(retval){printf("Database connection failed\n");return-1;}printf("Connection successful\n");// Create the SQL query for creating a tablecharcreate_table[100] ="CREATE TABLE IF NOT EXISTS users (uname TEXT PRIMARY KEY,pass TEXT NOT NULL,activated INTEGER)";// Execute the query for creating the tableretval = sqlite3_exec(handle,create_table,0,0,0);// Insert first row and second rowqueries[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 tablequeries[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 fetchedintcols = sqlite3_column_count(stmt);while(1){// fetch a row's statusretval = 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(intcol=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
1234Connection successfuluname = manish pass = mani activated =1uname = mehul pass = pulsar activated =0All rows fetched文件列表如下
12# lsbasics 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
#includeint 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
参考:
- 快速入门 http://www.sqlite.org/sqlite.html
- “SQLite header and source version mismatch” http://jianshusoft.blog.51cto.com/2380869/824575
- c语言的较为详细的例子 http://milky.manishsinha.net/2009/03/30/sqlite-with-c/
SQLite/嵌入式数据库的更多相关文章
- sqlite嵌入式数据库C语言基本操作(1)
sqlite嵌入式数据库C语言基本操作(1) :first-child{margin-top:0!important}img.plugin{box-shadow:0 1px 3px rgba(0,0, ...
- sqlite嵌入式数据库C语言基本操作(2)
:first-child{margin-top:0!important}img.plugin{box-shadow:0 1px 3px rgba(0,0,0,.1);border-radius:3px ...
- sqlite嵌入式数据库简介及特性
p.p1 { margin: 0; font: 12px "Helvetica Neue"; color: rgba(69, 69, 69, 1) } p.p2 { margin: ...
- [国嵌攻略][182][Sqlite嵌入式数据库移植]
数据库系统构成 在计算机系统中,保存数据的方式一般有两种: 1.普通文件方式 2.数据库方式 相比于普通文件方式,使用数据库来管理大批量数据具有更高的效率与安全性. 数据库系统一般由三个部分构成 1. ...
- Sqlite嵌入式数据库讲解
在计算机系统中,保存数据的方式一般有两种:1. 普通文件方式2. 数据库方式 相比于普通文件方式,使用数据库来管理大批量数据具有更高的效率与安全性. 数据库系统一般由3个部分构成1. 数据库2. 数据 ...
- [Sqlite]-->嵌入式数据库事务理解以及实例操作
引子: 1. Sqlite在Windows.Linux 和 Mac OS X 上的安装过程 2,嵌入式数据库的安装.建库.建表.更新表结构以及数据导入导出等等具体过程记录 SQLite 事务(Tran ...
- SQLite -- 嵌入式关系型数据库
SQLite -- 嵌入式关系型数据库 1.SQLite的数据类型:Typelessness(无类型) 1,能够保存不论什么类型的数据到表的随意列中 2.支持常见的类型如: NULL, VARCHAR ...
- 数据持久化之嵌入式数据库 SQLite(三)
阿里P7Android高级架构进阶视频免费学习请点击:https://space.bilibili.com/474380680 SQLite 是 D. Richard Hipp 用 C 语言编写的开源 ...
- Android SQLite (一) 数据库简介
大家好,今天来介绍一下SQLite的相关知识,并结合Java实现对SQLite数据库的操作. SQLite是D.Richard Hipp用C语言编写的开源嵌入式数据库引擎.它支持大多数的SQL92标准 ...
随机推荐
- Python 数据分析(一) 本实验将学习 pandas 基础,数据加载、存储与文件格式,数据规整化,绘图和可视化的知识
第1节 pandas 回顾 第2节 读写文本格式的数据 第3节 使用 HTML 和 Web API 第4节 使用数据库 第5节 合并数据集 第6节 重塑和轴向旋转 第7节 数据转换 第8节 字符串操作 ...
- 基于visual Studio2013解决C语言竞赛题之0703乾坤大挪移
题目
- 服务列表 - Sina App Engine
服务列表 - Sina App Engine 短信服务 新浪无线短信服务是由新浪无线提供的综合性短信服务. 使用服务 下载SDK: php 服务首页 方法 新浪无线短信服务是由新浪无线提供的综合性短信 ...
- The type MultipartEntity is deprecated
在HttpCient4.3之前上传文件主要使用MultipartEntity这个类,但如今这个类已经不在推荐使用了(过时了).随之替代它的类是MultipartEntityBuilder.关于Mult ...
- C# - InnerList
运行效果: 代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; name ...
- .NET vs JAVA
一个同事写一个方案,让我补充下.NET和 JAVA语言的优缺点,以下是我的回复: 老X你好! 我觉得这个问题,本质上不是java和.net两个开发语言方面的比较,单纯从这两个开发语言来讲,部分伯仲,在 ...
- Qt中Ui名字空间以及setupUi函数的原理和实现
用最新的QtCreator选择GUI的应用会产生含有如下文件的工程 下面就简单分析下各部分的功能. .pro文件是供qmake使用的文件,不是本文的重点[不过其实也很简单的],在此不多赘述. 所以呢, ...
- 算法-最长子序列和C/C++实现(三个复杂度)
最长子序列和的问题非常easy: 就是一个数组,求出当中当中连续的某一段和,而这一段和是全部的连续段和的最大的值.求出这个值. 先说复杂度最高的:O(n3) 直接上代码,非常easy的: // // ...
- java-多线程安全问题
1. 安全问题产生原因 多个线程操作共享数据. 操作共享数据的线程代码有多条.当一个线程在执行操作共享数据的多条代码过程中,其他线程参与了计算,就会产生线程安全问题. 2. 解决方案 java中用同步 ...
- Java多线程-实例解析
Java多线程实例 3种实现方法Java中的多线程有三种实现方式:1.继承Thread类,重写run方法.Thread本质上也是一个实现了Runnable的实例,他代表一个线程的实例,并且启动线程的唯 ...