sqlite3-实现C++类封装

前端之家收集整理的这篇文章主要介绍了sqlite3-实现C++类封装前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

、前言:

今天试了下如何用C++类实现接口封装,感觉蛮好 。用于封装的类主要有两个,sqliteStatement类和sqliteWrapper类,是一个老外写的。我看了下源码,主要是对C接口进行了封装,好处自然不用说,可以重用。很佩服老外的技巧,在这里就引用下他们的代码供大家分享下他们的思想。

代码链接:http://www.adp-gmbh.ch/sqlite/wrapper.html

二、类源码:

1.头文件sqliteWrapper.h

1/*
2 sqliteWrapper.h
3
4 Copyright (C) 2004 René Nyffenegger
5
6 This source code is provided 'as-is',without any express or implied
7 warranty. In no event will the author be held liable for any damages
8 arising from the use of this software.
9
10 Permission is granted to anyone to use this software for any purpose,
11 including commercial applications,and to alter it and redistribute it
12 freely,subject to the following restrictions:
13
14 1. The origin of this source code must not be misrepresented; you must not
15 claim that you wrote the original source code. If you use this source code
16 in a product,an acknowledgment in the product documentation would be
17 appreciated but is not required.
18
19 2. Altered source versions must be plainly marked as such,and must not be
20 misrepresented as being the original source code.
21
22 3. This notice may not be removed or altered from any source distribution.
23
24 René Nyffenegger rene.nyffenegger@adp-gmbh.ch
25
*/
26
27 #ifndef sqlITE_WRAPPER_H__
28#define sqlITE_WRAPPER_H__
29
30 #include <string>
31 #include <vector>
32
33 #include "sqlite3.h"
34
35class sqliteStatement{
36private:
37// sqliteStatement's ctor only to be called by sqliteWrapper
38 friend class sqliteWrapper;
39 sqliteStatement(std::stringconst& statement,sqlite3* db);
40
41public:
42 sqliteStatement();
43
44enum dataType{
45 INT=sqlITE_INTEGER,
46 FLT=sqlITE_FLOAT,128); line-height:1.5!important">47 TXT=sqlITE_TEXT,128); line-height:1.5!important">48 BLB=sqlITE_BLOB,128); line-height:1.5!important">49 NUL=sqlITE_NULL,128); line-height:1.5!important">50 };
51
52 dataType DataType(int pos_zero_indexed);
53
54int ValueInt(55 std::string ValueString(56
57 sqliteStatement(const sqliteStatement&);58~sqliteStatement();
59
60sqliteStatement& operator=(sqliteStatement const&);61
62bool Bind(int pos_zero_indexed,std::const& value);
63double value);
64int value);
65bool BindNull(66
67bool Execute();
68
69bool NextRow();
70
71 Call Reset if not depending on the NextRow cleaning up.
72 For example for select count(*) statements
73bool Reset();
74
75bool RestartSelect();
76
7778void DecreaseRefCounter();79
80int* ref_counter_; not yet used...81 sqlite3_stmt* stmt_;
82 };
83
84class sqliteWrapper {
8586 sqliteWrapper();
87
88bool Open(std::const& db_file);
89
90class ResultRecord {
9192 std::vector<std::string> fields_;
93 };
94
95class ResultTable {
96 friend 9798 ResultTable():ptr_cur_record_(0){}
99
100 std::vector<ResultRecord> records_;
101
102 ResultRecord* next(){
103if (ptr_cur_record_<records_.size()){
104return&(records_[ptr_cur_record_++]);
105 }
106return0;
107 }
108
109110void reset(){
111 records_.clear();
112 ptr_cur_record_=113 }
114
115116 unsigned int ptr_cur_record_;
117 };
118
119bool SelectStmt(std::const& stmt,ResultTable& res);
120bool DirectStatement(std::const& stmt);
121 sqliteStatement* Statement(std::122
123 std::string LastError();
124
125 Transaction related126bool Begin();
127bool Commit();
128bool Rollback();
129
130131
132staticint SelectCallback(void*p_data,255); line-height:1.5!important">int num_fields,255); line-height:1.5!important">char**p_fields,255); line-height:1.5!important">char**p_col_names);
133
134 sqlite3* db_;
135 };
136
137#endif

2.类实现文件sqliteWrapper.cpp


2
sqliteWrapper.cpp
3
4 Copyright (C) 2004 René Nyffenegger
5
6 This source code is provided 'as-is',and must not be
20 misrepresented as being the original source code.
21
22 3. This notice may not be removed or altered from any source distribution.
23
24 René Nyffenegger rene.nyffenegger@adp-gmbh.ch
25
26
27
28 #include sqliteWrapper.h29 TODO: raus30 #include <windows.h>
31
32 sqliteWrapper::sqliteWrapper():db_(0){
33 }
bool sqliteWrapper::Open(std::const& db_file){
if(sqlite3_open(db_file.c_str(),&db_)!=sqlITE_OK){
returnfalse;
38 }
39true;
40 }
41
42bool sqliteWrapper::SelectStmt(std::& res){
43char*errmsg;
int ret;
45
46 res.reset();
47
48 ret=sqlite3_exec(db_,stmt.c_str(),SelectCallback,static_cast<void*>(&res),&errmsg);
49
50if (ret!=sqlITE_OK){
5152 }
53 if (ret != sqlITE_OK) {55 std::cout << stmt << " [" << errmsg << "]" << std::endl;56 }57 }
58
59 TODO parameter p_col_namesint sqliteWrapper::SelectCallback(char** p_col_names) {
61 ResultTable* res=reinterpret_cast<ResultTable*>(p_data);
62
63 ResultRecord record;
64
65 #ifdef sqlITE_WRAPPER_REPORT_COLUMN_NAMES
66 Hubert Castelain: column names in the first row of res if res is empty67
68if(res->records_.size()==0) {
69 ResultRecord col_names;
for(int i=0;i<num_fields;i++){
72if(p_fields[i])
73 col_names.fields_.push_back(p_col_names[i]);
74else
75 col_names.fields_.push_back((null)"); or what else ?76 }
77 res->records_.push_back(col_names);
78 }
79#endif
80
810;i<num_fields;i++) {
82 Hubert Castelain: special treatment if null8384 record.fields_.push_back(p_fields[i]);
86 record.fields_.push_back(<null>");
87 }
88
89 res->records_.push_back(record);
90
92 }
93
94 sqliteStatement* sqliteWrapper::Statement(std::const& statement){
95 sqliteStatement* stmt;
96try{
97 stmt=new sqliteStatement(statement,db_);
98return stmt;
99 }
100catch(constchar* e){
101102 }
103 }
104
105 sqliteStatement::sqliteStatement(std::sqlite3* db) {
if(sqlite3_prepare(
107 db,128); line-height:1.5!important">108 statement.c_str(),0); line-height:1.5!important"> stmt109-1,0); line-height:1.5!important">读取的字节长度,若小于0,则终止;若大于0,则为能读取的最大字节数110&stmt_,0); line-height:1.5!important">用来指向输入参数中下一个需要编译的sql语句存放的sqlite statement对象的指针1110指针:指向stmt未编译的部分112 )
113!=sqlITE_OK){
114throw sqlite3_errmsg(db);
115 }
116
117if(!stmt_){
118throwstmt_ is 0";
119 }
120 }
121
122 sqliteStatement::~sqliteStatement(){
123
语法: int sqlite3_finalize(sqlite3_stmt *pStmt);if(stmt_) sqlite3_finalize(stmt_);
127 }
128
129 sqliteStatement::sqliteStatement():
130 stmt_(0)
131 {
132 }
134bool sqliteStatement::Bind(const& value){
135if (sqlite3_bind_text(
136 stmt_,128); line-height:1.5!important">137 pos_zero_indexed+ 通配符索引138 value.c_str(),128); line-height:1.5!important">139 value.length(),0); line-height:1.5!important"> 文本长度140 sqlITE_TRANSIENT sqlITE_TRANSIENT: sqlite 自我复制141 )
142!=sqlITE_OK) {
143144 }
145146 }
147
148double value) {
149if(sqlite3_bind_double(
150 stmt_,128); line-height:1.5!important">151 pos_zero_indexed+152 value
153 )
154!=sqlITE_OK) {
155156 }
157158 }
159
160int value) {
161if (sqlite3_bind_int(
162 stmt_,128); line-height:1.5!important">163 pos_zero_indexed+164 value
165 )
166!=sqlITE_OK){
167168 }
169170 }
171
172bool sqliteStatement::BindNull(int pos_zero_indexed){
173if (sqlite3_bind_null(
174 stmt_,128); line-height:1.5!important">175 pos_zero_indexed+176 )
177!=sqlITE_OK) {
178179 }
180181 }
182
183bool sqliteStatement::Execute() {
184int rc=sqlite3_step(stmt_);
185if (rc==sqlITE_BUSY){
186 ::MessageBox(0,sqlITE_BUSY",128); line-height:1.5!important">0);
187188 }
189if(rc==sqlITE_ERROR){
190 ::MessageBox(sqlITE_ERROR191192 }
193if(rc==sqlITE_MISUSE){
194 ::MessageBox(195196 }
197if(rc!=sqlITE_DONE){
198sqlite3_reset(stmt_);199200 }
201 sqlite3_reset(stmt_);
202203 }
204
205 sqliteStatement::dataType sqliteStatement::DataType(206return dataType(sqlite3_column_type(stmt_,pos_zero_indexed));
207 }
208
209int sqliteStatement::ValueInt(210return sqlite3_column_int(stmt_,pos_zero_indexed);
211 }
212
213 std::string sqliteStatement::ValueString(214return std::string(reinterpret_cast<char*>(sqlite3_column_text(stmt_,pos_zero_indexed)));
215 }
216
217bool sqliteStatement::RestartSelect(){
218 sqlite3_reset(stmt_);
219220 }
221
222bool sqliteStatement::Reset(){
223224
225 sqlite3_reset(stmt_);
226
227if (rc==sqlITE_ROW) 228229 }
230
231bool sqliteStatement::NextRow() {
232233
234if (rc==sqlITE_ROW){
235236 }
237if(rc==sqlITE_DONE){
238 sqlite3_reset(stmt_);
239240 }
241else242 ::MessageBox(sqliteStatement::NextRow sqlITE_MISUSE243 }
244if(rc==sqlITE_BUSY){
245 ::MessageBox(sqliteStatement::NextRow sqlITE_BUSY246 }
247248 ::MessageBox(sqliteStatement::NextRow sqlITE_ERROR249 }
250251 }
252
253bool sqliteWrapper::DirectStatement(std::const& stmt){
254255256
257 ret=sqlite3_exec(db_,128); line-height:1.5!important">258
259if(ret!=sqlITE_OK) {
260261 }
262263
264if(ret != sqlITE_OK) {265266}267 }
268
269 std::string sqliteWrapper::LastError(){
270return sqlite3_errmsg(db_);
271 }
272
273bool sqliteWrapper::Begin(){
274return DirectStatement(begin275 }
276
277bool sqliteWrapper::Commit(){
278commit279 }
280
281bool sqliteWrapper::Rollback(){
282rollback283 }
3.实例文件

3.1 创建数据库数据库表:Create_DB_Table.cpp


2 *
功能:创建数据库数据库表。
3 * open():若指定数据库不存在,则创建;否则打开
4 * DirectStatement():可以用于执行大部分sql语句,但对SELECT语句有些例外。
5 *
6
7 #include <iostream>
8 #include 9
10int main() {
11 sqliteWrapper sqlite;
12if (sqlite.Open(sqliteWrapper.db")) {
13 std::cout<<sqliteWrapper.db created or opened"<<std::endl;
14 }
15else {
16 std::cout<<couldn't open sqliteWrapper.db17 }
18
19if(sqlite.DirectStatement(Create table foo(bar,baz)")){
20 std::cout<<table foo created21 }
2223 std::cout<<couldn't insert into foo24
2526 }
3.2 插入数据:Insert_DB_Data.cpp


2 *
功能:向数据库表插入记录
3 *
4 5 #include <iostream>
6
7 #include 8
910 sqliteWrapper sqlite;
1112 std::cout<<13 }
1415 std::cout<<16 }
17
18insert into foo values(1,2)19 std::cout<<values(1,2) into foo inserted20
3.3 绑定参数执行:Bind_Param_Execute.cpp


2 *
功能:Bind()封装sqlite3_bind_*系列函数,类中表现为重载函数,给sql声明中的通配符赋值,若未绑定,则为空
3 * Execute():实现sqlite3_step(s) 和sqlite3_reset(s)机制。
4
int main(){
if(sqlite.Open(else{
18 sqliteStatement* stmt=sqlite.Statement(insert into foo values(?,?)19
20if(stmt->Bind(3)){
21 std::cout<<value 3 successfully bound at pos 022 }
2324 std::cout<<value 3 NOT successfully bound at pos 0: "<<sqlite.LastError()<<std::endl;
25 }
264)){
27 std::cout<<value 4 successfully bound at pos 128 }
30 std::cout<<value 4 NOT successfully bound at pos 1:31 }
33 第一次执行Execute34if(stmt->Execute()){
35 std::cout<<statement executed36 }
38 std::cout<<error executing statement: 39 }
5)){
42 std::cout<<value 5 successfully bound at pos 043 }
45 std::cout<<value 5 NOT successfully bound at pos 046 }
486)){
49 std::cout<<value 6 successfully bound at pos 150 }
52 std::cout<<value 6 NOT successfully bound at pos 153 }
54
第二次执行Execute57 std::cout<<58 }
60 std::cout<<61 }
64 }
3.4 输出数据库数据:Print_DB_Data.cpp


2 *
功能:演示了使用类成员函数获取数据库表的数据,并将数据输出到屏幕
3 * Statement():返回一个指向sqliteStatement类的指针
4 * NextRow():只要数据未取完,就返回True
5 * DataType():返回访问列的数据类型
6 * ValueString():返回std::string.
7
8 #include <iostream>
9 #include 10
12 sqliteWrapper sqlite;
1314 std::cout<<15 }
1617 std::cout<<18 }
20 sqliteStatement* stmt=sqlite.Statement(select * from foo21
while(stmt->NextRow()){
23 std::cout<<stmt->DataType (0)<< - "<<stmt->DataType (1) << | "<<
24 stmt->ValueString("<<stmt->ValueString(1)<<std::endl;
2728 }

猜你在找的Sqlite相关文章