C/C++下使用SQLite轻量级数据库

 
一、SQLite
SQLite,是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来讲,它的处理速度比他们都快。SQLite
 也被用于很多软件,打开飞信的安装目录,就能看见 SQLite ,估计是被用来存储聊天记录的。
二、下载SQLite
我下的版本为sqlite-amalgamation-3071400.zip,这个包含了主要的源代码。sqlite-dll-win32-x86-3071400.zip这个是Windows下的编译好的DLL文件和def文件,解压缩后包含两个文件,sqlite3.def和sqlite3.dll。
 
编译源代码很简单,新建立一个C++空项目,把sqlite-amalgamation-3071400.zip解压缩后的文件拷进去,编译、链接,就行了。我的目的是把sqlite数据库作为自己项目中的一部分,是作为嵌入的一部分使用的。这个要利用到sqlite3.dll文件。可是源文件只有sqlite3.def和sqlite3.dll没有sqlite3.lib文件,怎么用呢?根据def文件可以生成对应的LIB文件。以下是命令行生成LIB文件。找到VS的安装路径,我的是D:\Program
 Files\,用命令行进入以下路径。
 
D:\Program Files\Microsoft Visual Studio 9.0\VC\bin>lib /def:sqlite3.def /machine:ix86
 
三、使用
 
View Code
//[cpp] view plaincopyprint?
//#pragma comment(lib,"sqlite3.lib")  
#include <iostream>  
#include <string>  
#include <sstream>  
#include "sqlite3.h"  
  
using namespace std;  
  
sqlite3* pDB;  
static int callback(void *NotUsed, int argc, char **argv, char **azColName)  
{  
    int i =0;  
    std::cout<< azColName[i] << " = "<< (argv[i] ? argv[i] : "NULL")<< ", " ;  
    std::cout<< "\n";  
    return 0;  
}  
int main()  
{  
    int res = sqlite3_open("mydatabase.db", &pDB);  
    if( res ){  
        std::cout << "Can't open database: "<< sqlite3_errmsg(pDB);  
        sqlite3_close(pDB);  
        return -1;  
    }  
    char* errMsg;  
    string dropTab="drop table test;";  
    string createStrSQL= "create table test(one int, two long);";  
    int res;  
    res = sqlite3_exec(pDB,dropTab.c_str(),0,0, &errMsg);  
    if (res != SQLITE_OK)  
    {  
        std::cout << "执行SQL出错." << errMsg << std::endl;  
        return -1;  
    }  
    res = sqlite3_exec(pDB,createStrSQL.c_str(),0,0, &errMsg);  
    if (res != SQLITE_OK)  
    {  
        std::cout << "执行创建table的SQL出错." << errMsg << std::endl;  
        return -1;  
    }  
    else  
        std::cout << "创建table的SQL成功执行."<< std::endl;  
  
    for (int i= 1; i < 10; ++i)  
    {  
        stringstream strsql;  
        strsql << "insert into test values(";  
        strsql  << i << ","<< (i+10) << ");";  
        std::string str = strsql.str();  
        res = sqlite3_exec(pDB,str.c_str(),0,0, &errMsg);  
        if (res != SQLITE_OK)  
        {  
            std::cout << "执行SQL出错." << errMsg << std::endl;  
            return -1;  
        }  
    }  
    string strSQL= "select * from test;";  
    int res = sqlite3_exec(pDB,strSQL.c_str(),callback,0, &errMsg);  
    if (res != SQLITE_OK)  
    {  
        std::cout << "执行SQL出错." << errMsg << std::endl;  
        return -1;  
    }  
    else  
        std::cout << "SQL成功执行."<< std::endl;  
    return 0;  
}  

 记在这里,学习啊!

原文地址:https://www.cnblogs.com/pmars/p/2724773.html