1. 程式人生 >實用技巧 >其它 >SQLite3單例模式(C++)

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 [email protected] -lsqlite3  #注意這裡記得加-lsqlite3
$(objects):
clean:
        rm -f $(objects) $(ELF)

(不會Makefile的可以看我部落格:MakeFile工具使用)

編譯結果:

SQLite3單例模式(C++)