Archive for September 18, 2008

SQLITE3的C++简单封装类

几年前写过一个简单的sqlite3读写,非常简陋,bug在所难免,旨在给初学者一点帮助,欢迎高手交流


// mySQLITE3.hpp
// 该文件在visual c++ 6.0和c++ builder 6.0上均编译通过,在我自己的程序上运行好几年了
#ifndef __MY_SQLITE3_HPP__
#define __MY_SQLITE3_HPP__
#include "sqlite3_lib\sqlite3.h"
#ifdef
//---------------------------------------------------------------------------
class TMySQLite3
{
private:
sqlite3* _db; // 数据库实例
char* _errmsg; // 错误信息
char** _dbResult; // 记录集
public:
TMySQLite3() { _db=NULL; _errmsg=NULL; }
// 释放时,要先释放表并关闭数据库
~TMySQLite3() {
if (_dbResult) {
sqlite3_free_table(_dbResult);
}
if (_db) {
sqlite3_close(_db);
}
}
// 打开数据库
bool OpenDB(char* FullDBPath) {
int result = sqlite3_open(FullDBPath, &_db);
if (result!=SQLITE_OK) return false;
return true;
}
// 取数据记录
char** FetchRecord(char* SQL, int* Row, int* Col) {
int result = sqlite3_get_table(_db, SQL, &_dbResult, Row, Col, &_errmsg);
if (result==SQLITE_OK) return _dbResult;
else return NULL;
}
// 释放记录集
void FreeRecord() {
sqlite3_free_table(_dbResult);
_dbResult = NULL;
}
// 执行SQL语句
bool ExecSQL(char* SQL) {
int result = sqlite3_exec(_db, SQL, NULL, NULL, &_errmsg);
if (result!=SQLITE_OK) return false;
return true;
}
// 取得错误信息
char* GetMessage() {
return _errmsg;
}
};

#endif

下面是一段测试代码,Visual C++ 6.0的工程里面提炼出来的,供参考。

TMySQLite3 *pLite;
pLite = new TMySQLite3(); // 创建实例
// 打开数据库文件
if (pLite->OpenDB("E:\\task.db")==false) {
AfxMessageBox(pLite->GetMessage());
}
char** rs = NULL;
int nRow=0, nCol=0;
// 打开数据集
rs = pLite->FetchRecord("select * from t_task", &nRow, &nCol);
if (rs==NULL) AfxMessageBox(pLite->GetMessage());
else {
int nIndex=nCol;
// 循环输出每行数据
for (int i=0; i<nRow; i++) {
fprintf(stderr, "[%s]\t-\t[%s]\t-\t[%s]", rs[nIndex], rs[nIndex+1], rs[nIndex+2]);
nIndex += nCol;
}
pLite->FreeRecord();
}
if (pLite) {
delete pLite;
pLite = NULL;
}

t_task的建表脚本可以如下

CREATE TABLE t_task
(
taskid    integer not null,
tasktitle varchar(255) not null,
tasktype  char(2) not null,
taskdate  char(8) null
)
CREATE UNIQUE INDEX idx_task ON t_task(taskid)

Leave a Comment