代码拉取完成,页面将自动刷新
//Author: [email protected]
//Use of this source code is governed by a BSD-style license
#ifndef SQLITEDB_H
#define SQLITEDB_H
#include<string>
#include<memory>
#include<list>
#include<vector>
#include<tuple>
typedef struct sqlite3 sqlite3;
class PreparedStatement;
class SqliteDB
{
public:
explicit SqliteDB(const std::string &db_file);
SqliteDB(const SqliteDB&)=delete;
SqliteDB& operator = (const SqliteDB&)=delete;
~SqliteDB();
int close();
int execute(const std::string &sql);
const char* errorMsg();
std::weak_ptr<PreparedStatement> createPreparedStatement(const std::string &sql);
//对应语句 insert into student(id, name, score) values('001', 'aa', 81),('002', 'bb', 82);
template<typename ... Args>
int executemany(const std::string &sql, const std::vector<std::tuple<Args...>> ¶m);
//对应语句 insert into student(id, name, score) select '001', 'aa', 81 union all select '002', 'bb', 82;
template<typename ... Args>
int executemany2(const std::string &sql, const std::vector<std::tuple<Args...>> ¶m);
private:
int closeConn();
private:
template<typename T>
static std::string valueToString(const T &val)
{
return std::to_string(val);
}
static std::string valueToString(const std::string &val)
{
return "'" + val + "'";
}
template<typename Tuple, std::size_t N>
struct TuplePrinter
{
static std::string print(const Tuple &t)
{
std::string ret = TuplePrinter<Tuple, N-1>::print(t);
ret += ", " + valueToString(std::get<N-1>(t));
return ret;
}
};
template<typename Tuple>
struct TuplePrinter<Tuple, 1>
{
static std::string print(const Tuple &t)
{
return valueToString(std::get<0>(t));
}
};
private:
sqlite3 *m_conn = nullptr;
std::list<std::shared_ptr<PreparedStatement>> m_stmt_list;
};
template<typename ... Args>
int SqliteDB::executemany(const std::string &sql, const std::vector<std::tuple<Args...>> ¶m)
{
std::string sql_param;
sql_param.reserve(param.size() * 20);
for(const auto &e : param)
{
sql_param += "(" + TuplePrinter<decltype(e), sizeof...(Args)>::print(e) + "),";
}
sql_param.pop_back();
return execute(sql + " values " + sql_param);
}
template<typename ... Args>
int SqliteDB::executemany2(const std::string &sql, const std::vector<std::tuple<Args...>> ¶m)
{
std::string sql_param;
sql_param.reserve(param.size() * 20);
for(const auto &e : param )
{
sql_param += " select " + TuplePrinter<decltype(e), sizeof...(Args)>::print(e) + " union all ";
}
auto pos = sql_param.rfind("union all");
if( pos != std::string::npos )//删除最后一个多余的"union all"
sql_param.erase(pos);
return execute(sql + sql_param);
}
#endif // SQLITEDB_H
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。