easysqlite mysql_持久化存储SQLite的两种C++封装(easySQLite 和 cppSQLite)

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.

sqlite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。

由于使C API, 有很多优秀的对sqlITE进行的封装,今天就介绍两种 easysqlite和cppsqlite。

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

//

// Copyright (C) 2010 Piotr Zagawa

//

// Released under BSD License

//

#pragma once

#include

#include

#include

#include

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

//--------------------------

//string

typedef std::string string;

//integer

#if defined(_MSC_VER) || defined(__BORLANDC__)

typedef __int64 integer;

#else

typedef long long int integer;

#endif

//time

class 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 class

class 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& vector,const char* sep = ",");

//sql eof

};

用Field 对象定义一个表结构

sqlField.h

#pragma once

#include "sqlCommon.h"

namespace sql

{

class Field

{

public:

friend class FieldSet;

private:

string _name;

field_use _use;

field_type _type;

int _index;

int _flags;

public:

Field(field_use use);

Field(string name,field_type type,int flags = flag_none);

Field(const Field& value);

public:

bool isKeyIdField();

bool isEndingField();

public:

int getIndex();

string getName() const;

string getTypeStr();

field_type getType();

bool isPrimaryKey();

bool isNotNull();

public:

string getDefinition();

static Field* createFromDefinition(string value);

};

//sql eof

};

先定义一个Database对象,然后打开进行操作

sqlDatabase.h

//

// Copyright (C) 2010 Piotr Zagawa

//

// Released under BSD License

//

#pragma once

#include "sqlite3.h"

#include "sqlCommon.h"

namespace sql

{

class Database

{

private:

sqlite3* _db;

string _err_msg;

int _result_open;

public:

Database(void);

~Database(void);

public:

sqlite3* getHandle();

string errMsg();

bool open(string filename);

void close();

bool isOpen();

public:

bool transactionBegin();

bool transactionCommit();

bool transactionRollback();

};

//sql eof

};

通过Table对象来操作数据库了

sqlTable.h

//

// Copyright (C) 2010 Piotr Zagawa

//

// Released under BSD License

//

#pragma once

#include "sqlite3.h"

#include "sqlCommon.h"

#include "sqlFieldSet.h"

#include "sqlRecordSet.h"

namespace sql

{

class Table

{

private:

sqlite3* _db;

string _tableName;

RecordSet _recordset;

public:

Table(sqlite3* db,string tableName,Field* definition);

Table(sqlite3* db,FieldSet* fields);

public:

string name();

string getDefinition();

string toString();

string errMsg();

FieldSet* fields();

sqlite3* getHandle();

public:

bool create();

bool exists();

bool remove();

bool truncate();

public:

bool open();

bool open(string whereCondition);

bool open(string whereCondition,string sortBy);

bool query(string queryStr);

int totalRecordCount();

public:

int recordCount();

Record* getRecord(int record_index);

Record* getTopRecord();

Record* getRecordByKeyId(integer keyId);

public:

bool addRecord(Record* record);

bool updateRecord(Record* record);

bool deleteRecords(string whereCondition);

bool copyRecords(Table& source);

bool backup(Table& source);

public:

static Table* createFromDefinition(sqlite3* db,string fieldsDefinition);

};

如果要修改/添加/删除数据,您可以使用Record对象来完成

sqlRecord.h

//

// Copyright (C) 2010 Piotr Zagawa

//

// Released under BSD License

//

#pragma once

#include

#include "sqlCommon.h"

#include "sqlValue.h"

#include "sqlFieldSet.h"

namespace sql

{

class Record

{

private:

FieldSet* _fields;

std::vector _values;

public:

Record(FieldSet* fields);

Record(Record* record);

Record(const Record& record);

private:

friend class RecordSet;

void initColumnCount(int columns);

void initColumnValue(int column_index,char* value,field_type type);

public:

int columnCount();

Value* getValue(int column_index);

Value* getValue(string fieldName);

Value* getValue(const Field& field);

Value* getKeyIdValue();

Field* fieldByName(string fieldName);

FieldSet* fields();

string toString();

string tosql();

bool equalsColumnValue(Record* record,string fieldName);

bool equalsValues(Record* record);

public:

string tosqlInsert(string tableName);

string tosqlUpdate(string tableName);

public:

void setNull(int index);

void setString(int index,string value);

void setInteger(int index,integer value);

void setDouble(int index,double value);

void setBool(int index,bool value);

void setTime(int index,time value);

public:

void setNull(string fieldName);

void setString(string fieldName,string value);

void setInteger(string fieldName,integer value);

void setDouble(string fieldName,double value);

void setBool(string fieldName,bool value);

void setTime(string fieldName,time value);

public:

void setNull(Field& field);

void setString(Field& field,string value);

void setInteger(Field& field,integer value);

void setDouble(Field& field,double value);

void setBool(Field& field,bool value);

void setTime(Field& field,time value);

};

//sql eof

};

应用:

//define table structure

Field definition_tbPerson[] =

{

Field(FIELD_KEY),Field("fname",flag_not_null),Field("lname",Field("birthdate",type_time),Field(DEFINITION_END),};

//define database object

sql::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());

}

Cppsqlite

Cppsqlite3.h

///

// Cppsqlite3 - A C++ wrapper around the sqlite3 embedded database library.

//

#ifndef _Cppsqlite3_H_

#define _Cppsqlite3_H_

#include "sqlite3.h"

#include

#include

#define CPPsqlITE_ERROR 1000

class 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

应用:

#include "Cppsqlite.h"

#include

#include

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值