sqlite is an in-process library that implements a self-contained,serverless,zero-configuration,transactional sql database engine. The code for sqlite is in the public domain and is thus free for use for any purpose,commercial or private. sqlite is the most wIDely deployed database in the world with more applications than we can count,including several high-profile projects.
http://www.sqlite.org/
sqlite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。
由于使C API, 有很多优秀的对sqlITE进行的封装,今天就介绍两种 easysqlite和cppsqlite。
easysqlite为什么easysqlite优于其他封装?
(https://code.google.com/archive/p/easysqlite/ 哈哈,不敢苟同,反正挺好用的)
elegant,objective solution (优雅的面向对象解决方案)
explicit naming and calling (显式命名和调用)
uses exceptions or methods return values (使用异常以及方法返回值)
clear,understandable usage (容易理解)
flexible and expandable (灵活而且可扩展)
strongly tested (tests included) (经过强测试)
easysqlite里面有一些类:
这里就简单展示几个而已:
sqlCommon.h
@H_301_54@//// copyright (C) 2010 Piotr Zagawa//// Released under BSD license//#pragma once#include <string>#include <vector>#include <stdio.h>#include <time.h>namespace sql{//fIEld state enums//--------------------------enum fIEld_use{ FIELD_DEFAulT,FIELD_KEY,DEFinitioN_END,};enum fIEld_type{ type_undefined,type_int,type_text,type_float,type_bool,type_time,};enum fIEld_flags{ flag_none = 0,flag_not_null = 1,flag_primary_key = 2,};//common data types//--------------------------//stringtypedef std::string string;//integer#if defined(_MSC_VER) || defined(__BORLANDC__)typedef __int64 integer;#elsetypedef long long int integer;#endif//timeclass time{private: time_t _value;private: string format(const char* format);public: time(); time(const time& value); time(integer value); time& operator=(const time& value); bool operator==(const time& value); static time Now();public: double diff(time& value); time_t get(); voID addValue(integer value); voID addMinutes(integer count); voID addHours(integer count); voID addDays(integer count);public: integer asInteger(); string asstring(); string asTimeString(); string asDateString();};//common exception classclass Exception{private: string _msg;public: Exception(string msg) : _msg(msg) { }; string msg() { return _msg; }};//comment this directive to disable exceptions//#define USE_EXCEPTIONS#ifndef THROW_EXCEPTION #ifdef USE_EXCEPTIONS #define THROW_EXCEPTION(msg) throw Exception(msg); #else #define THROW_EXCEPTION(msg) #endif#endif//utils//--------------------------class log{public: log(std::string s) { std::string text = s; text += "\r\n"; printf("%s",text.c_str()); }};string intToStr(int value);string intToStr(integer value);string quoteStr(string value);string binToHex(const char* buffer,int size);string generateSHA(string& value);string& trimleft(string& s);string& trimright(string& s);string& trim(string& s);string trim(const string& s);voID ListToVector(string s,std::vector<string>& vector,const char* sep = ",");//sql eof};用FIEld 对象定义一个表结构
sqlFIEld.h
先定义一个Database对象,然后打开进行 *** 作
sqlDatabase.h
通过table对象来 *** 作数据库了
sqltable.h
如果要修改/添加/删除数据,您可以使用Record对象来完成
sqlRecord.h
应用:
@H_301_54@//define table structureFIEld deFinition_tbPerson[] ={ FIEld(FIELD_KEY),FIEld("fname",flag_not_null),FIEld("lname",FIEld("birthdate",type_time),FIEld(DEFinitioN_END),};//define database objectsql::Database db;try{ //open database file db.open("test.db"); //define table object table tbPerson(db.getHandle(),"person",deFinition_tbPerson); //remove table from database if exists if (tbPerson.exists()) tbPerson.remove(); //create new table tbPerson.create(); //define new record Record record(tbPerson.fIElds()); //set record data record.setString("fname","Jan"); record.setString("lname","Kowalski"); record.setTime("birthdate",time::Now()); //add 10 records for (int index = 0; index < 10; index++) tbPerson.addRecord(&record); //select record to update if (Record* record = tbPerson.getRecordByKeyID(7)) { record->setString("fname","Frank"); record->setString("lname","Sinatra"); record->setNull("birthdate"); tbPerson.updateRecord(record); } //load all records tbPerson.open(); //List loaded records for (int index = 0; index < tbPerson.recordCount(); index++) if (Record* record = tbPerson.getRecord(index)) sql::log(record->toString()); sql::log(""); sql::log("ALL OK");} catch (Exception e) { printf("ERROR: %s\r\n",e.msg().c_str());} Cppsqlitehttp://www.codeproject.com/Articles/6343/CppSQLite-C-Wrapper-for-SQLite
Cppsqlite3.h
@H_301_54@///////////////////////////////////////////////////////////////////////////////// Cppsqlite3 - A C++ wrapper around the sqlite3 embedded database library.//#ifndef _Cppsqlite3_H_#define _Cppsqlite3_H_#include "sqlite3.h"#include <cstdio>#include <cstring>#define CPPsqlITE_ERROR 1000class Cppsqlite3Exception{public: Cppsqlite3Exception(const int nErrCode,char* szErrMess,bool bDeleteMsg=true); Cppsqlite3Exception(const Cppsqlite3Exception& e); virtual ~Cppsqlite3Exception(); const int errorCode() { return mnErrCode; } const char* errorMessage() { return mpszErrMess; } static const char* errorCodeAsstring(int nErrCode);private: int mnErrCode; char* mpszErrMess;};class Cppsqlite3Buffer{public: Cppsqlite3Buffer(); ~Cppsqlite3Buffer(); const char* format(const char* szFormat,...); operator const char*() { return mpBuf; } voID clear();private: char* mpBuf;};class Cppsqlite3Binary{public: Cppsqlite3Binary(); ~Cppsqlite3Binary(); voID setBinary(const unsigned char* pBuf,int nLen); voID setEncoded(const unsigned char* pBuf); const unsigned char* getEncoded(); const unsigned char* getBinary(); int getBinaryLength(); unsigned char* allocBuffer(int nLen); voID clear();private: unsigned char* mpBuf; int mnBinaryLen; int mnBufferLen; int mnEncodedLen; bool mbEncoded;};class Cppsqlite3query{public: Cppsqlite3query(); Cppsqlite3query(const Cppsqlite3query& rquery); Cppsqlite3query(sqlite3* pDB,sqlite3_stmt* pVM,bool bEof,bool bOwnVM=true); Cppsqlite3query& operator=(const Cppsqlite3query& rquery); virtual ~Cppsqlite3query(); int numFIElds(); int fIEldindex(const char* szFIEld); const char* fIEldname(int nCol); const char* fIEldDeclType(int nCol); int fIEldDataType(int nCol); const char* fIEldValue(int nFIEld); const char* fIEldValue(const char* szFIEld); int getIntFIEld(int nFIEld,int nNullValue=0); int getIntFIEld(const char* szFIEld,int nNullValue=0); sqlite_int64 getInt64FIEld(int nFIEld,sqlite_int64 nNullValue=0); sqlite_int64 getInt64FIEld(const char* szFIEld,sqlite_int64 nNullValue=0); double getfloatFIEld(int nFIEld,double fNullValue=0.0); double getfloatFIEld(const char* szFIEld,double fNullValue=0.0); const char* getStringFIEld(int nFIEld,const char* szNullValue=""); const char* getStringFIEld(const char* szFIEld,const char* szNullValue=""); const unsigned char* getBlobFIEld(int nFIEld,int& nLen); const unsigned char* getBlobFIEld(const char* szFIEld,int& nLen); bool fIEldisNull(int nFIEld); bool fIEldisNull(const char* szFIEld); bool eof(); voID nextRow(); voID finalize();private: voID checkVM(); sqlite3* mpDB; sqlite3_stmt* mpVM; bool mbEof; int mnCols; bool mbOwnVM;};class Cppsqlite3table{public: Cppsqlite3table(); Cppsqlite3table(const Cppsqlite3table& rtable); Cppsqlite3table(char** paszResults,int nRows,int nCols); virtual ~Cppsqlite3table(); Cppsqlite3table& operator=(const Cppsqlite3table& rtable); int numFIElds(); int numRows(); const char* fIEldname(int nCol); const char* fIEldValue(int nFIEld); const char* fIEldValue(const char* szFIEld); int getIntFIEld(int nFIEld,int nNullValue=0); double getfloatFIEld(int nFIEld,const char* szNullValue=""); bool fIEldisNull(int nFIEld); bool fIEldisNull(const char* szFIEld); voID setRow(int nRow); voID finalize();private: voID checkResults(); int mnCols; int mnRows; int mnCurrentRow; char** mpaszResults;};class Cppsqlite3Statement{public: Cppsqlite3Statement(); Cppsqlite3Statement(const Cppsqlite3Statement& rStatement); Cppsqlite3Statement(sqlite3* pDB,sqlite3_stmt* pVM); virtual ~Cppsqlite3Statement(); Cppsqlite3Statement& operator=(const Cppsqlite3Statement& rStatement); int execDML(); Cppsqlite3query execquery(); voID bind(int nParam,const char* szValue); voID bind(int nParam,const int nValue); voID bind(int nParam,const double DWValue); voID bind(int nParam,const unsigned char* blobValue,int nLen); voID bindNull(int nParam); int bindParameterIndex(const char* szParam); voID bind(const char* szParam,const char* szValue); voID bind(const char* szParam,const int nValue); voID bind(const char* szParam,const double DWValue); voID bind(const char* szParam,int nLen); voID bindNull(const char* szParam); voID reset(); voID finalize();private: voID checkDB(); voID checkVM(); sqlite3* mpDB; sqlite3_stmt* mpVM;};class Cppsqlite3DB{public: Cppsqlite3DB(); virtual ~Cppsqlite3DB(); voID open(const char* szfile); voID close(); bool tableExists(const char* sztable); int execDML(const char* szsql); Cppsqlite3query execquery(const char* szsql); int execScalar(const char* szsql,int nNullValue=0); Cppsqlite3table gettable(const char* szsql); Cppsqlite3Statement compileStatement(const char* szsql); sqlite_int64 lastRowID(); voID interrupt() { sqlite3_interrupt(mpDB); } voID setBusyTimeout(int nMillisecs); static const char* sqliteVersion() { return sqlITE_VERSION; } static const char* sqliteheaderVersion() { return sqlITE_VERSION; } static const char* sqlitelibraryVersion() { return sqlite3_libversion(); } static int sqlitelibraryVersionNumber() { return sqlite3_libversion_number(); } bool IsautoCommitOn();private: Cppsqlite3DB(const Cppsqlite3DB& db); Cppsqlite3DB& operator=(const Cppsqlite3DB& db); sqlite3_stmt* compile(const char* szsql); voID checkDB(); sqlite3* mpDB; int mnBusyTimeoutMs;};#endif应用:
@H_301_54@#include "Cppsqlite.h"#include <ctime>#include <iostream>using namespace std;const char* gszfile = "C:\test.db";int main(int argc,char** argv){ try { int i,fld; time_t tmStart,tmEnd; CppsqliteDB db; cout << "sqlite Version: " << db.sqliteVersion() << endl; remove(gszfile); db.open(gszfile); cout << endl << "Creating emp table" << endl; db.execDML("create table emp(empno int,empname char(20));"); /////////////////////////////////////////////////////////////// // Execute some DML,and print number of rows affected by each one /////////////////////////////////////////////////////////////// cout << endl << "DML tests" << endl; int nRows = db.execDML("insert into emp values (7,'DavID Beckham');"); cout << nRows << " rows inserted" << endl; nRows = db.execDML( "update emp set empname = 'Christiano Ronaldo' where empno = 7;"); cout << nRows << " rows updated" << endl; nRows = db.execDML("delete from emp where empno = 7;"); cout << nRows << " rows deleted" << endl; ///////////////////////////////////////////////////////////////// // Transaction Demo // The transaction Could just as easily have been rolled back ///////////////////////////////////////////////////////////////// int nRowsToCreate(50000); cout << endl << "Transaction test,creating " << nRowsToCreate; cout << " rows please wait..." << endl; tmStart = time(0); db.execDML("begin transaction;"); for (i = 0; i < nRowsToCreate; i++) { char buf[128]; sprintf(buf,"insert into emp values (%d,'Empname%06d');",i,i); db.execDML(buf); } db.execDML("commit transaction;"); tmEnd = time(0); //////////////////////////////////////////////////////////////// // Demonstrate CppsqliteDB::execScalar() //////////////////////////////////////////////////////////////// cout << db.execScalar("select count(*) from emp;") << " rows in emp table in "; cout << tmEnd-tmStart << " seconds (that was fast!)" << endl; //////////////////////////////////////////////////////////////// // Re-create emp table with auto-increment fIEld //////////////////////////////////////////////////////////////// cout << endl << "auto increment test" << endl; db.execDML("drop table emp;"); db.execDML( "create table emp(empno integer primary key,empname char(20));"); cout << nRows << " rows deleted" << endl; for (i = 0; i < 5; i++) { char buf[128]; sprintf(buf,"insert into emp (empname) values ('Empname%06d');",i+1); db.execDML(buf); cout << " primary key: " << db.lastRowID() << endl; } /////////////////////////////////////////////////////////////////// // query data and also show results of inserts into auto-increment fIEld ////////////////////////////////////////////////////////////////// cout << endl << "Select statement test" << endl; Cppsqlitequery q = db.execquery("select * from emp order by 1;"); for (fld = 0; fld < q.numFIElds(); fld++) { cout << q.fIEldname(fld) << "(" << q.fIEldType(fld) << ")|"; } cout << endl; while (!q.eof()) { cout << q.fIEldValue(0) << "|"; cout << q.fIEldValue(1) << "|" << endl; q.nextRow(); } /////////////////////////////////////////////////////////////// // sqlite's printf() functionality. Handles embedded quotes and NulLs //////////////////////////////////////////////////////////////// cout << endl << "sqlite sprintf test" << endl; CppsqliteBuffer bufsql; bufsql.format("insert into emp (empname) values (%Q);","He's bad"); cout << (const char*)bufsql << endl; db.execDML(bufsql); bufsql.format("insert into emp (empname) values (%Q);",NulL); cout << (const char*)bufsql << endl; db.execDML(bufsql); //////////////////////////////////////////////////////////////////// // Fetch table at once,and also show how to // use Cppsqlitetable::setRow() method ////////////////////////////////////////////////////////////////// cout << endl << "gettable() test" << endl; Cppsqlitetable t = db.gettable("select * from emp order by 1;"); for (fld = 0; fld < t.numFIElds(); fld++) { cout << t.fIEldname(fld) << "|"; } cout << endl; for (int row = 0; row < t.numRows(); row++) { t.setRow(row); for (int fld = 0; fld < t.numFIElds(); fld++) { if (!t.fIEldisNull(fld)) cout << t.fIEldValue(fld) << "|"; else cout << "NulL" << "|"; } cout << endl; } //////////////////////////////////////////////////////////////////// // Test CppsqliteBinary by storing/retrIEving some binary data,checking // it afterwards to make sure it is the same ////////////////////////////////////////////////////////////////// cout << endl << "Binary data test" << endl; db.execDML("create table bindata(desc char(10),data blob);"); unsigned char bin[256]; CppsqliteBinary blob; for (i = 0; i < sizeof bin; i++) { bin[i] = i; } blob.setBinary(bin,sizeof bin); bufsql.format("insert into bindata values ('testing',%Q);",blob.getEncoded()); db.execDML(bufsql); cout << "Stored binary Length: " << sizeof bin << endl; q = db.execquery("select data from bindata where desc = 'testing';"); if (!q.eof()) { blob.setEncoded((unsigned char*)q.fIEldValue("data")); cout << "RetrIEved binary Length: " << blob.getBinaryLength() << endl; } const unsigned char* pbin = blob.getBinary(); for (i = 0; i < sizeof bin; i++) { if (pbin[i] != i) { cout << "Problem: i:," << i << " bin[i]: " << pbin[i] << endl; } } ///////////////////////////////////////////////////////// // Pre-compiled Statements Demo ///////////////////////////////////////////////////////////// cout << endl << "Transaction test,creating " << nRowsToCreate; cout << " rows please wait..." << endl; db.execDML("drop table emp;"); db.execDML("create table emp(empno int,empname char(20));"); tmStart = time(0); db.execDML("begin transaction;"); CppsqliteStatement stmt = db.compileStatement( "insert into emp values (?,?);"); for (i = 0; i < nRowsToCreate; i++) { char buf[16]; sprintf(buf,"Empname%06d",i); stmt.bind(1,i); stmt.bind(2,buf); stmt.execDML(); stmt.reset(); } db.execDML("commit transaction;"); tmEnd = time(0); cout << db.execScalar("select count(*) from emp;") << " rows in emp table in "; cout << tmEnd-tmStart << " seconds (that was even faster!)" << endl; cout << endl << "End of tests" << endl; } catch (CppsqliteException& e) { cerr << e.errorCode() << ":" << e.errorMessage() << endl; } //////////////////////////////////////////////////////////////// // Loop until user enters q or Q /////////////////////////////////////////////////////////// char c(' '); while (c != 'q' && c != 'Q') { cout << "Press q then enter to quit: "; cin >> c; } return 0;} 总结以上是内存溢出为你收集整理的持久化存储SQLite的两种C++封装(easySQLite 和 cppSQLite)全部内容,希望文章能够帮你解决持久化存储SQLite的两种C++封装(easySQLite 和 cppSQLite)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)