Skip to content

Instantly share code, notes, and snippets.

@takageymt
Created July 25, 2018 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takageymt/e0c956b9a088d6f551efa7695f9ad0a6 to your computer and use it in GitHub Desktop.
Save takageymt/e0c956b9a088d6f551efa7695f9ad0a6 to your computer and use it in GitHub Desktop.
#ifndef MY_DB_UTIL_HPP
#define MY_DB_UTIL_HPP
#include <iostream>
#include <stdexcept>
#include <exception>
#include <memory>
#include <string>
#include <sqlite3.h>
// http://d.hatena.ne.jp/tociyuki/20141218/1418914334
namespace sqlite3pp {
class statement {
private:
std::shared_ptr<struct sqlite3_stmt> mstmt;
public:
statement (sqlite3_stmt* pstmt) : mstmt (pstmt, sqlite3_finalize) { }
int reset () { return sqlite3_reset (mstmt.get ()); }
int clear_bindings () { return sqlite3_clear_bindings(mstmt.get ()); }
int bind (int n, int v) { return sqlite3_bind_int (mstmt.get (), n, v); }
int bind (int n, double v) { return sqlite3_bind_double (mstmt.get (), n, v); }
int bind (int n, std::string s) {
return sqlite3_bind_text (mstmt.get (), n, s.c_str (), (int)s.size (), SQLITE_TRANSIENT);
}
int step () { return sqlite3_step (mstmt.get ()); }
int column_int (int n) { return sqlite3_column_int (mstmt.get (), n); }
double column_double (int n) { return sqlite3_column_double (mstmt.get (), n); }
std::string column_string (int n)
{
return std::string((char const*)sqlite3_column_text (mstmt.get (), n),
sqlite3_column_bytes (mstmt.get (), n));
}
};
class connection {
private:
std::shared_ptr<struct sqlite3> mdb;
int mstatus;
public:
connection (std::string s)
{
sqlite3* db;
mstatus = sqlite3_open (s.c_str (), &db);
mdb = std::shared_ptr<struct sqlite3>(db, sqlite3_close);
}
statement prepare (std::string s)
{
sqlite3_stmt* stmt;
mstatus = sqlite3_prepare_v2 (mdb.get (), s.c_str (), s.size (), &stmt, 0);
return statement (stmt);
}
int status () { return mstatus; }
std::string errmsg () { return std::string (sqlite3_errmsg (mdb.get ())); }
sqlite3_int64 last_insert_rowid () { return sqlite3_last_insert_rowid (mdb.get ()); }
int execute (std::string s)
{
sqlite3_stmt* stmt;
mstatus = sqlite3_prepare_v2 (mdb.get (), s.c_str (), s.size (), &stmt, 0);
if (SQLITE_OK == mstatus)
mstatus = sqlite3_step (stmt);
if (SQLITE_DONE != mstatus && SQLITE_ROW != mstatus)
std::cerr << "sqlite3_execute: " << errmsg () << ": " << s << std::endl; /* 2014年12月19日修正 stmt -> s */
sqlite3_finalize (stmt);
return mstatus;
}
};
struct sqlerror : public std::exception {};
} // namespace sqlite3pp
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment