C++下使用sqlite简明示例

本文的工程文件可至http://download.csdn.net/detail/great3779/4317410免费下载。

 

Sqlite是一个开源的跨平台嵌入式数据库,采用C语言编写,它提供了c、 C++、C#、PHP、Java等版本及接口。以C版本为例,整个数据库仅由一个.h文件和一个.c文件构成。这个由不到20000行代码构成的数据库,能很好的支持标准的sql语句,并且还带事务处理功能。有兴趣的朋友可以看看它的源代码,代码严谨、结构精巧,不愧为大师之作!

 

C++中使用Sqlite的基本步骤:

1.      打开一个sqlite数据库(如果不存在,则自动创建)

sqlite3_open

2.      在数据库中创建一个表

sqlite3_exec(pSqlite3, "create table Table1(idinteger,name text,score real)", NULL, NULL, &sqlite3_errmsg)

3.      向表中插入数据

sqlite3_exec(pSqlite3, "insert intoTable1(id,name,score) values(1,'huangzhidan',92.5)", NULL, NULL, &sqlite3_errmsg);

4.      从表中查询数据. Sqlite使用回调函数的方式获取查询数据,具体使用方法可参考demo工程。

sqlite3_exec(pSqlite3, "select * from Table1",CBFunc, "hzd", &sqlite3_errmsg);

5.      关闭数据库

sqlite3_close(pSqlite3);

 

sqlite的事务处理

  sqlite3_exec(pSqlite3,"begin;", NULL, NULL, &sqlite3_errmsg);

  …执行事务…

  sqlite3_exec(pSqlite3,"commit;", NULL, NULL, &sqlite3_errmsg);

 

有一个第三方的工具SQLiteExpert,能可视化地查询sqlite数据库并显示查询结果,是sqlite的必备伴侣工具。SQLiteExpert可至http://www.onlinedown.net/soft/71562.htm下载。

它的使用也非常简单,打开数据库后,我们可以在左侧浏览器看到数据库中有多少张表。(如下图)

 

选中表后,我们可以在右侧的SQL中,输入查询语句进行数据库查询,待语句执行完毕后,在右侧的数据框中会展示查询结果。(见下图)

 

点击Data可以查看整个表的内容。

 

下面附上Demo程序的代码:

// sqlite.cpp : Defines the entrypoint for the console application.
//
 
#include "stdafx.h"
#include <sstream>
#include <iostream>
#include "sqlite3.h"
#include <vector>
#include <assert.h>
using namespace std;
 
// Create or Query
#define _CREATE
 
struct DATAS
{
 int id;
 string name;
 double score;
};
 
typedef vector<DATAS> ARR_DATA;
ARR_DATA gDatas;
 
// call back by sqlite
int CBFunc(void* msg, int column, char**column_string, char** column_title)
{
 assert(column == 3);
 
 DATAS data;
 
 for(int i = 0; i < column; ++i)
 {
   if(string(column_title[i]) == "id")
     data.id = atoi(column_string[i]);
   else if(string(column_title[i]) == "name")
     data.name = column_string[i];
   else if(string(column_title[i]) == "score")
     data.score = atof(column_string[i]);
 }
 
 gDatas.push_back(data);
 return 0;
}
 
int _tmain(int argc, _TCHAR* argv[])
{
 sqlite3* pSqlite3 = NULL; 
 char* sqlite3_errmsg = NULL;
 
 // database's name
 char* pStrDataBaseFile = "test.db";
 
 // test if sqlite is threadsafe
 // we can set SQLITE_THREADSAFE value to change this.
 int thread_safe_flag = sqlite3_threadsafe();
 
 // open a sqlite database
 if (SQLITE_OK == sqlite3_open(pStrDataBaseFile, &pSqlite3))
 {
#ifdef _CREATE
   // firstly, drop Table1 from database
   int ret = sqlite3_exec(pSqlite3, "drop table Table1", NULL, NULL,&sqlite3_errmsg);
 
   char* sql_create = "create table Table1(id integer,name text,scorereal)";
   // create Table1 in database
   ret = sqlite3_exec(pSqlite3, sql_create, NULL, NULL, &sqlite3_errmsg);
#endif
 }
 
 stringstream ss;
 
 // begin a transaction
 sqlite3_exec(pSqlite3, "begin;", NULL, NULL, &sqlite3_errmsg);
 
#ifdef _CREATE
 int loop = 1000;
 for(int i = 0; i < loop; ++i)
 {
   ss.str("");
   ss << "insert into Table1(id,name,score) values("<< i << ",'huangzhidan'," << (double)rand()*100/RAND_MAX<< ")";
 
   string te = ss.str();
 
   // insert some data into database
   sqlite3_exec(pSqlite3, ss.str().c_str(), NULL, NULL, &sqlite3_errmsg);
 
   // show progress
   if(i % (loop/100) == 0)
     cout << i << endl;
 }
#else
 // query data from database
 // "hzd" is callback flag
 sqlite3_exec(pSqlite3, "select * from Table1", CBFunc,"hzd", &sqlite3_errmsg);
#endif
 
 // end transaction
 sqlite3_exec(pSqlite3, "commit;", NULL, NULL, &sqlite3_errmsg);
 
 // free memory
 sqlite3_free(sqlite3_errmsg);
 
 // close database
 sqlite3_close(pSqlite3);
 
 // output result
 cout << "ARRAY size: " << gDatas.size() << endl;
 
         return0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLite3是一款轻量级的关系型数据库管理系统,它是以C语言写成的,并且提供了C语言的API接口。要在C++使用SQLite3,可以使用SQLite C/C++接口,该接口包含在SQLite3的源代码中,可以通过下载SQLite3的源码来获得。 以下是在C++使用SQLite3的基本步骤: 1. 下载SQLite3的源代码并解压缩。 2. 在C++项目中添加SQLite3的源代码文件。 3. 在需要使用SQLite3的地方包含SQLite3的头文件: ```c++ #include <sqlite3.h> ``` 4. 打开数据库连接: ```c++ sqlite3* db; int rc = sqlite3_open("database.db", &db); if(rc != SQLITE_OK) { // 连接失败 } ``` 这里的`database.db`是数据库文件的名称,如果该文件不存在,则会自动创建。 5. 执行SQL语句: ```c++ char* errmsg; int rc = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)", nullptr, nullptr, &errmsg); if(rc != SQLITE_OK) { // 执行SQL语句失败 } ``` 上面的SQL语句创建了一个名为`users`的表,该表包含三个字段:`id`、`name`和`age`。 6. 查询数据: ```c++ sqlite3_stmt* stmt; int rc = sqlite3_prepare_v2(db, "SELECT * FROM users", -1, &stmt, nullptr); if(rc != SQLITE_OK) { // 查询失败 } while(sqlite3_step(stmt) == SQLITE_ROW) { int id = sqlite3_column_int(stmt, 0); const char* name = (const char*)sqlite3_column_text(stmt, 1); int age = sqlite3_column_int(stmt, 2); // 处理查询结果 } sqlite3_finalize(stmt); ``` 上面的代码查询了`users`表中的所有数据,并逐行读取数据。`sqlite3_prepare_v2`函数用于准备SQL语句,`sqlite3_step`函数用于执行SQL语句并读取结果,`sqlite3_finalize`函数用于释放资源。 7. 关闭数据库连接: ```c++ sqlite3_close(db); ``` 关闭数据库连接会释放所有相关资源,包括打开的文件句柄、内存等。 SQLite3的API接口非常简单,使用起来也比较方便,但需要注意的是,SQLite3不支持并发访问,因此在多线程环境中使用时需要注意线程安全问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值