blob: b46c133168a6d5e2f8370724246207efa1ed0ed5 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
/*
* connection.h
*
* Created on: 28.10.2012
* Author: savop
*/
#ifndef CONNECTION_H_
#define CONNECTION_H_
#include <string>
#include <boost/shared_ptr.hpp>
#include <sqlite3.h>
#include "exception.h"
#include "statement.h"
namespace db {
class Connection {
private:
boost::shared_ptr<sqlite3> m_connection;
public:
Connection() {}
Connection(boost::shared_ptr<sqlite3>& conn)
: m_connection(conn)
{}
virtual ~Connection(){}
void Close(){
m_connection.reset();
}
Statement Prepare(const std::string& stmt){
sqlite3_stmt* _stmt;
if(sqlite3_prepare(m_connection.get(), stmt.c_str(), stmt.length(), &_stmt, NULL) != SQLITE_OK)
throw SQLiteException(sqlite3_errmsg(m_connection.get()));
boost::shared_ptr<sqlite3_stmt> statement(_stmt, std::ptr_fun(sqlite3_finalize));
return Statement(m_connection, statement);
}
int Execute(const std::string& stmt){
return Prepare(stmt).Execute();
}
void BeginTransaction(){
Execute("BEGIN TRANSACTION");
}
void CommitTransaction(){
Execute("COMMIT TRANSACTION");
}
void RollbackTransaction(){
Execute("ROLLBACK TRANSACTION");
}
};
Connection Connect(const std::string url){
sqlite3* _conn;
if(sqlite3_open_v2(url.c_str(), &_conn, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL) != SQLITE_OK){
sqlite3_close(_conn);
throw SQLiteException(std::string("Failed to open ") + url);
}
boost::shared_ptr<sqlite3> connection(_conn, std::ptr_fun(sqlite3_close));
return Connection(connection);
}
} // namespace db
#endif /* CONNECTION_H_ */
|