SQLite3单例模式(C++)
Posted 别呀
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQLite3单例模式(C++)相关的知识,希望对你有一定的参考价值。
注意:这代码只能在linux底下运行。
.h
文件 (我的文件是mysql.h)
#ifndef MYSQL_H
#define MYSQL_H
#include <sqlite3.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
class MySql
{
public:
static MySql *Instance() //获取唯一单例对象
{
if(!m_sql)
m_sql = new MySql();
return m_sql;
}
void Init(const char* fileName); //初始化
void InsertData(); //插入数据
void SelectData(int id); //通过id查询数据
private:
MySql(); //私有 防止外部调用
~MySql();
static MySql* m_sql; //静态指针保存单例对象
static sqlite3 * db; //数据库类指针
char *Sql_statement; //存放执行语句
sqlite3_stmt *stmt; //标记数据库的执行信息
int rc; //执行返回结果
};
#endif // MYSQL_H
.cpp
文件 (我的文件是MySql.cpp)
#include "MySql.h"
sqlite3 *MySql::db;
MySql *MySql::m_sql = NULL;
MySql::MySql()
{
Sql_statement = new char[1024];
memset(Sql_statement,0,1024);
this->Init("data.db");
}
MySql::~MySql()
{
delete []this->Sql_statement;
}
//初始化,打开数据库、创建表
void MySql::Init(const char* fileName)
{
this->rc = sqlite3_open(fileName,&db);
if(this->rc == SQLITE_OK)
{
strcpy(this->Sql_statement,"create table student(id int primary key,name text,age int)");
this->rc = sqlite3_exec(db,Sql_statement,NULL,NULL,&errMes);
if(rc == SQLITE_OK)
{
printf("Success to create table!\\n");
}
memset(Sql_statement,0,1024);
}
}
//向表中插入数据
void MySql::InsertData()
{
strcpy(this->Sql_statement,"insert into student values(1,'zhangsan',20)");
sqlite3_exec(db,this->Sql_statement,NULL,NULL,&errMes);
strcpy(this->Sql_statement,"insert into student values(2,'lisi',19)");
sqlite3_exec(db,this->Sql_statement,NULL,NULL,&errMes);
if(rc == SQLITE_OK)
{
printf("Success to insert data!\\n");
}
memset(Sql_statement,0,1024);
}
//通过id查询数据
void MySql::SelectData(int id)
{
const unsigned char *name;
int nid = 0;
int age = 0;
sprintf(this->Sql_statement,"select * from student where id = %d",id);
sqlite3_prepare(db,this->Sql_statement,-1,&this->stmt,NULL);
while(sqlite3_step(this->stmt) == SQLITE_ROW)
{
nid = sqlite3_column_int(this->stmt, 0);
name = sqlite3_column_text(this->stmt, 1);
age = sqlite3_column_int(this->stmt, 2);
printf("name:%s ,id:%d ,age:%d\\n",name,nid,age);
}
}
main.cpp
文件
#include "MySql.h"
#include <iostream>
using namespace std;
int main()
{
MySql::Instance()->InsertData();
MySql::Instance()->SelectData(1);
return 0;
}
最后把这三个文件放在linux的同一目录底下,然后通过makefile
工具进行编译。
MakeFile
文件
ELF=main
CC=g++
src=$(wildcard *.cpp)
objects=$(src:.cpp=.o)
$(ELF):$(objects)
$(CC) $^ -o $@ -lsqlite3 #注意这里记得加-lsqlite3
$(objects):
clean:
rm -f $(objects) $(ELF)
(不会Makefile的可以看我博客:MakeFile工具使用)
编译结果:
以上是关于SQLite3单例模式(C++)的主要内容,如果未能解决你的问题,请参考以下文章