源代码链接: http://www.adp-gmbh.ch/sqlite/wrapper.html
/*
SQLiteWrapper.h
Copyright (C) 2004 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
#ifndef SQLITE_WRAPPER_H__
#define SQLITE_WRAPPER_H__
#include <string>
#include <vector>
#include "sqlite3.h"
class SQLiteStatement {
private:
// SQLiteStatement's ctor only to be called by SQLiteWrapper
friend class SQLiteWrapper;
SQLiteStatement(std::string const& statement, sqlite3* db);
public:
SQLiteStatement();
enum dataType {
INT = SQLITE_INTEGER,
FLT = SQLITE_FLOAT ,
TXT = SQLITE_TEXT ,
BLB = SQLITE_BLOB ,
NUL = SQLITE_NULL ,
};
dataType DataType(int pos_zero_indexed);
int ValueInt (int pos_zero_indexed);
std::string ValueString(int pos_zero_indexed);
// SQLiteStatement(const SQLiteStatement&);
~SQLiteStatement();
//SQLiteStatement& operator=(SQLiteStatement const&);
bool Bind (int pos_zero_indexed, std::string const& value);
bool Bind (int pos_zero_indexed, double value);
bool Bind (int pos_zero_indexed, int value);
bool BindNull(int pos_zero_indexed);
bool Execute();
bool NextRow();
/* Call Reset if not depending on the NextRow cleaning up.
For example for select count(*) statements*/
bool Reset();
bool RestartSelect();
private:
//void DecreaseRefCounter();
//int* ref_counter_; // not yet used...
sqlite3_stmt* stmt_;
};
class SQLiteWrapper {
public:
SQLiteWrapper();
bool Open(std::string const& db_file);
class ResultRecord {
public:
std::vector<std::string> fields_;
};
class ResultTable {
friend class SQLiteWrapper;
public:
ResultTable() : ptr_cur_record_(0) {}
std::vector<ResultRecord> records_;
ResultRecord* next() {
if (ptr_cur_record_ < records_.size()) {
return &(records_[ptr_cur_record_++]);
}
return 0;
}
private:
void reset() {
records_.clear();
ptr_cur_record_=0;
}
private:
unsigned int ptr_cur_record_;
};
bool SelectStmt (std::string const& stmt, ResultTable& res);
bool DirectStatement (std::string const& stmt);
SQLiteStatement* Statement(std::string const& stmt);
std::string LastError();
// Transaction related
bool Begin ();
bool Commit ();
bool Rollback();
private:
static int SelectCallback(void *p_data, int num_fields, char **p_fields, char **p_col_names);
sqlite3* db_;
};
#endif
/*
SQLiteWrapper.cpp
Copyright (C) 2004 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
#include "SQLiteWrapper.h"
// TODO: raus
#include <windows.h>
SQLiteWrapper::SQLiteWrapper() : db_(0) {
}
bool SQLiteWrapper::Open(std::string const& db_file) {
if (sqlite3_open(db_file.c_str(), &db_) != SQLITE_OK) {
return false;
}
return true;
}
bool SQLiteWrapper::SelectStmt(std::string const& stmt, ResultTable& res) {
char *errmsg;
int ret;
res.reset();
ret = sqlite3_exec(db_, stmt.c_str(), SelectCallback, static_cast<void*> (&res), &errmsg);
if (ret != SQLITE_OK) {
return false;
}
return true;
// if (ret != SQLITE_OK) {
// std::cout << stmt << " [" << errmsg << "]" << std::endl;
// }
}
// TODO parameter p_col_names
int SQLiteWrapper::SelectCallback(void *p_data, int num_fields, char **p_fields, char** p_col_names) {
ResultTable* res = reinterpret_cast<ResultTable*>(p_data);
ResultRecord record;
#ifdef SQLITE_WRAPPER_REPORT_COLUMN_NAMES
// Hubert Castelain: column names in the first row of res if res is empty
if(res->records_.size()==0) {
ResultRecord col_names;
for(int i=0; i < num_fields; i++) {
if(p_fields[i]) col_names.fields_.push_back (p_col_names[i]);
else
col_names.fields_.push_back("(null)"); // or what else ?
}
res->records_.push_back(col_names);
}
#endif
for(int i=0; i < num_fields; i++) {
// Hubert Castelain: special treatment if null
if (p_fields[i]) record.fields_.push_back(p_fields[i]);
else record.fields_.push_back("<null>");
}
res->records_.push_back(record);
return 0;
}
SQLiteStatement* SQLiteWrapper::Statement(std::string const& statement) {
SQLiteStatement* stmt;
try {
stmt = new SQLiteStatement(statement, db_);
return stmt;
}
catch (const char* e) {
return 0;
}
}
SQLiteStatement::SQLiteStatement(std::string const& statement, sqlite3* db) {
if ( sqlite3_prepare(
db,
statement.c_str(), // stmt
-1, // If than zero, then stmt is read up to the first nul terminator
&stmt_,
0 // Pointer to unused portion of stmt
)
!= SQLITE_OK) {
throw sqlite3_errmsg(db);
}
if (!stmt_) {
throw "stmt_ is 0";
}
}
SQLiteStatement::~SQLiteStatement() {
// Hubert Castelain 28/8/2005
// Prevent the database remaining locked after some statement.
// syntax: int sqlite3_finalize(sqlite3_stmt *pStmt);
if(stmt_) sqlite3_finalize(stmt_);
}
SQLiteStatement::SQLiteStatement() :
stmt_ (0)
{
}
bool SQLiteStatement::Bind(int pos_zero_indexed, std::string const& value) {
if (sqlite3_bind_text (
stmt_,
pos_zero_indexed+1, // Index of wildcard
value.c_str(),
value.length(), // length of text
SQLITE_TRANSIENT // SQLITE_TRANSIENT: SQLite makes its own copy
)
!= SQLITE_OK) {
return false;
}
return true;
}
bool SQLiteStatement::Bind(int pos_zero_indexed, double value) {
if (sqlite3_bind_double(
stmt_,
pos_zero_indexed+1, // Index of wildcard
value
)
!= SQLITE_OK) {
return false;
}
return true;
}
bool SQLiteStatement::Bind(int pos_zero_indexed, int value) {
if (sqlite3_bind_int(
stmt_,
pos_zero_indexed+1, // Index of wildcard
value
)
!= SQLITE_OK) {
return false;
}
return true;
}
bool SQLiteStatement::BindNull(int pos_zero_indexed) {
if (sqlite3_bind_null(
stmt_,
pos_zero_indexed+1 // Index of wildcard
)
!= SQLITE_OK) {
return false;
}
return true;
}
bool SQLiteStatement::Execute() {
int rc = sqlite3_step(stmt_);
if (rc == SQLITE_BUSY) {
::MessageBox(0, "SQLITE_BUSY", 0, 0);
return false;
}
if (rc == SQLITE_ERROR) {
::MessageBox(0, "SQLITE_ERROR", 0, 0);
return false;
}
if (rc == SQLITE_MISUSE) {
::MessageBox(0, "SQLITE_ERROR", 0, 0);
return false;
}
if (rc != SQLITE_DONE) {
//sqlite3_reset(stmt_);
return false;
}
sqlite3_reset(stmt_);
return true;
}
SQLiteStatement::dataType SQLiteStatement::DataType(int pos_zero_indexed) {
return dataType(sqlite3_column_type(stmt_, pos_zero_indexed));
}
int SQLiteStatement::ValueInt(int pos_zero_indexed) {
return sqlite3_column_int(stmt_, pos_zero_indexed);
}
std::string SQLiteStatement::ValueString(int pos_zero_indexed) {
return std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt_, pos_zero_indexed)));
}
bool SQLiteStatement::RestartSelect() {
sqlite3_reset(stmt_);
return true;
}
bool SQLiteStatement::Reset() {
int rc = sqlite3_step(stmt_);
sqlite3_reset(stmt_);
if (rc == SQLITE_ROW) return true;
return false;
}
bool SQLiteStatement::NextRow() {
int rc = sqlite3_step(stmt_);
if (rc == SQLITE_ROW ) {
return true;
}
if (rc == SQLITE_DONE ) {
sqlite3_reset(stmt_);
return false;
}
else if (rc == SQLITE_MISUSE) {
::MessageBox(0, "SQLiteStatement::NextRow SQLITE_MISUSE", 0, 0);
}
else if (rc == SQLITE_BUSY ) {
::MessageBox(0, "SQLiteStatement::NextRow SQLITE_BUSY", 0, 0);
}
else if (rc == SQLITE_ERROR ) {
::MessageBox(0, "SQLiteStatement::NextRow SQLITE_ERROR", 0, 0);
}
return false;
}
bool SQLiteWrapper::DirectStatement(std::string const& stmt) {
char *errmsg;
int ret;
ret = sqlite3_exec(db_, stmt.c_str(), 0, 0, &errmsg);
if(ret != SQLITE_OK) {
return false;
}
return true;
//if(ret != SQLITE_OK) {
// std::cout << stmt << " [" << errmsg << "]" << std::endl;
//}
}
std::string SQLiteWrapper::LastError() {
return sqlite3_errmsg(db_);
}
bool SQLiteWrapper::Begin() {
return DirectStatement("begin");
}
bool SQLiteWrapper::Commit() {
return DirectStatement("commit");
}
bool SQLiteWrapper::Rollback() {
return DirectStatement("rollback");
}
SQLite Wrapper, Test 1 Test 1 demonstrates SQLiteWrapper::Open() and SQLiteWrapper::DirectStatement() Open(), obviously, opens the database. If it doesn't exist, it is first created, then opened. DirectStatement() can be used to execute any SQL statement. It doesn't make much sense for select statements, however, as the data won't be returned. It is assumed that the database SQLiteWrapper.db doesn't yet exist, so it is created. Then, a table (named foo) is created. This table will then be used in test 2 to insert some values. Test 4 shows how to select from that table. test_1.cpp #include <iostream> #include "SQLiteWrapper.h" int main() { SQLiteWrapper sqlite; if (sqlite.Open("SQLiteWrapper.db")) { std::cout << "SQLiteWrapper.db created or opened" << std::endl; } else { std::cout << "couldn't open SQLiteWrapper.db" << std::endl; } if (sqlite.DirectStatement("create table foo (bar, baz)")) { std::cout << "table foo created" << std::endl; } else { std::cout << "Couldn't create table foo" << std::endl; } return 0; }
SQLite Wrapper, test 2 As does test 1, this program only used Open() and DirectStatement(). DirectStatement is used to insert the data without binding. Test 3 will again insert some values, but does so with binding the values. It is assumed that a database with the name SQLiteWrapper.db is already created and that it contains a table named foo. (This is done with test 1). test_2.cpp #include <iostream> #include "SQLiteWrapper.h" int main() { SQLiteWrapper sqlite; if (sqlite.Open("SQLiteWrapper.db")) { std::cout << "SQLiteWrapper.db created or opened" << std::endl; } else { std::cout << "couldn't open SQLiteWrapper.db" << std::endl; } if (sqlite.DirectStatement("insert into foo values (1, 2)")) { std::cout << "values (1,2) into foo inserted" << std::endl; } else { std::cout << "Couldn't insert into foo" << std::endl; } return 0; }
SQLite Wrapper, test 3 This test demonstrates Statement(), Bind() and Execute(). It is assumed that a database with the name SQLiteWrapper.db is already created and that it contains a table named foo. (This is done with test 1). test_3.cpp #include <iostream> #include "SQLiteWrapper.h" int main() { SQLiteWrapper sqlite; if (sqlite.Open("SQLiteWrapper.db")) { std::cout << "SQLiteWrapper.db created or opened" << std::endl; } else { std::cout << "couldn't open SQLiteWrapper.db" << std::endl; } SQLiteStatement* stmt = sqlite.Statement("insert into foo values (?, ?)"); if (stmt->Bind(0, 3)) { std::cout << "value 3 successfully bound at pos 0" << std::endl; } else { std::cout << "value 3 NOT successfully bound at pos 0: " << sqlite.LastError() << std::endl; } if (stmt->Bind(1, 4)) { std::cout << "value 4 successfully bound at pos 1" << std::endl; } else { std::cout << "value 4 NOT successfully bound at pos 1:" << sqlite.LastError() << std::endl; } // ******************************** Executing 1st time if (stmt->Execute()) { std::cout << "statement executed" << std::endl; } else { std::cout << "error executing statement: " << sqlite.LastError() << std::endl; } if (stmt->Bind(0, 5)) { std::cout << "value 5 successfully bound at pos 0" << std::endl; } else { std::cout << "value 5 NOT successfully bound at pos 0" << std::endl; } if (stmt->Bind(1, 6)) { std::cout << "value 6 successfully bound at pos 1" << std::endl; } else { std::cout << "value 6 NOT successfully bound at pos 1" << std::endl; } // ******************************** Executing 2nd time if (stmt->Execute()) { std::cout << "statement executed" << std::endl; } else { std::cout << "error executing statement: " << sqlite.LastError() << std::endl; } return 0; }
SQLite Wrapper, test 4 This test demonstrates how values can be selected from a table using SQLiteWrapper::Statement(), SQLiteWrapper::NextRow(), SQLiteWrapper::DataType() and SQLiteWrapper::ValueString(). Statement() returns a pointer to a SQLiteStatement. The values for the the select statement can then be retrieved through that returned class. NextRow() returns true as long as there are still records to be fetched. DataType() returns the datatype for the passed column. ValueString() returns the value as std::string. It is assumed that a database with the name SQLiteWrapper.db is already created and that it contains a table named foo. (This is done with test 1, test 2 and test 3). test_4.cpp #include <iostream> #include "SQLiteWrapper.h" int main() { SQLiteWrapper sqlite; if (sqlite.Open("SQLiteWrapper.db")) { std::cout << "SQLiteWrapper.db created or opened" << std::endl; } else { std::cout << "couldn't open SQLiteWrapper.db" << std::endl; } SQLiteStatement* stmt = sqlite.Statement("select * from foo"); while (stmt->NextRow()) { std::cout << stmt->DataType (0) << " - " << stmt->DataType (1) << " | " << stmt->ValueString(0) << " - " << stmt->ValueString(1) << std::endl; } return 0; }