blob: 5ab9db1e6ee41a23063527510078aee15abd90b4 [file] [log] [blame]
shockjianga5ae48c2014-07-27 23:21:41 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
3 * Copyright (c) 2014, Regents of the University of California.
4 *
5 * This file is part of NDNS (Named Data Networking Domain Name Service).
6 * See AUTHORS.md for complete list of NDNS authors and contributors.
7 *
8 * NDNS is free software: you can redistribute it and/or modify it under the terms
9 * of the GNU General Public License as published by the Free Software Foundation,
10 * either version 3 of the License, or (at your option) any later version.
11 *
12 * NDNS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
13 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along with
17 * NDNS, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include <iostream>
21#include <fstream>
22
23#include "db-mgr.hpp"
24
25namespace ndn {
26namespace ndns {
27
28DBMgr::DBMgr()
29: m_dbfile("src/db/ndns-local.db")
30, m_conn(0)
31, m_reCode(-1)
32, m_status(DBClosed)
33, m_resultNum(0)
34{
35 std::fstream file;
36 file.open(m_dbfile,std::ios::in);
37 if (file)
38 {
39 std::cout<<"database file "<<m_dbfile<<" does exist"<<std::endl;
40 } else
41 {
42 std::cout<<"database file "<<m_dbfile<<" does not exist"<<std::endl;
43 }
44
45}
46
47
48DBMgr::~DBMgr()
49{
50}
51
52void DBMgr::open()
53{
54 if (m_status == DBConnected)
55 return;
56
57 m_reCode = sqlite3_open(this->m_dbfile.c_str(), &(this->m_conn));
58 if (m_reCode != SQLITE_OK)
59 {
60 m_err = "Cannot connect to the db: "+this->m_dbfile;
61 m_status = DBError;
62 //exit(1);
63 }else
64 {
65 std::cout<<"connect to the db: "<<m_dbfile<<std::endl;
66 }
67 m_status = DBConnected;
68}
69
70void DBMgr::close()
71{
72 if (m_status == DBClosed)
73 return;
74
75 m_reCode = sqlite3_close(this->m_conn);
76 if (m_reCode != SQLITE_OK)
77 {
78 m_err = "Cannot close the db: "+this->m_dbfile;
79 m_status = DBError;
80 }
81 m_status = DBClosed;
82}
83
84void DBMgr::execute(std::string sql, int (*callback)(void*,int,char**,char**), void * paras)
85{
86 if (m_status == DBClosed)
87 this->open();
88
89 clearResultNum();
90 char *err_msg;
91 m_reCode = sqlite3_exec(m_conn, sql.c_str(), callback, paras, &err_msg);
92 if (m_reCode != SQLITE_OK)
93 {
94 m_status = DBError;
95 this->m_err.append(err_msg);
96 std::cout<<this->m_err<<std::endl;
97 }
98 this->close();
99}
100
101}//namespace ndns
102}//namespace ndn
103