cocos2dx学习笔记:sqlite3封装的简单工具类

---使用说明sql

都是静态方法,直接用便可,以下:数据库

Sql::open("PopStar");
Sql::setInt(101,lv);
Sql::setString("starData",starData.c_str());
Sql::createTable("User", "create table User(id integer,name text)");
Sql::exec("delete from User where id=1");//增、删、改的语句能够直接使用这个方法
Sql::exec("select * from User", loadRecordForString, &get);//查找的语句须要加个回调来处理数据
Sql::close();


---Sql.h函数

#ifndef _SQL_H_
#define _SQL_H_
#include "cocos2d.h"
#pragma comment(lib, "sqlite3")
using namespace std;
class Sql{
public:
	static void open(const char* sqlName);//打开数据库,传入数据库名称
	static void exec(string sql);//执行sql语句
	static void exec(string sql, int(*callback)(void*, int, char**, char**) , void* arg);//执行sql语句,有回调
	static void close();//关闭,最好在操做完数据库后及时关闭
	//---如下是一些简单经常使用的方法---
	static bool isTableExist(string tableName);//判断该表是否存在
	static void createTable(string tableName, string sql);//在不存在该表的状况下建立该表,须要传入表名、建立表的sql语句
	static bool deleteTable(string tableName);
	static int getDataCount(string tableName);//获取该表的行数
	//---存一些简单的数据的时候,无需手动建立表,功能相似UserDefault---
	static void setInt(int key,int value);
	static int getInt(int key,int defaultValue);
	static void setString(string key, string value);
	static string getString(string key, string defaultValue);
};
#endif //_SQL_H_

---Sql.cpp优化

#include "Sql.h"
#include "sqlite3\include\sqlite3.h"
#include <stdlib.h>
#pragma comment(lib, "sqlite3")
USING_NS_CC;

sqlite3* pDB = NULL;//数据库指针
char* errMsg = NULL;//错误信息
std::string sqlstr;//SQL指令
int result;//返回值

const char* simpleTableNameInt = "SimpleTableInt";
const char* simpleTableNameString = "SimpleTableString";

//打开数据库
void Sql::open(const char* sqlName){
	//打开一个数据库,若是该数据库不存在,会自动建立一个
	result = sqlite3_open(sqlName,&pDB);
	if (result != SQLITE_OK){
		CCLOG("open sqlite fail,code:%d,cause:%s\n",result,errMsg);
	}
	else{
		CCLOG("open sqlite success:%s",sqlName);
	}
	//目前只有int,以后会陆续优化改进
	sqlstr = String::createWithFormat("create table %s(key integer,value integer)", simpleTableNameInt)->_string;
	createTable(simpleTableNameInt, sqlstr);
	sqlstr = String::createWithFormat("create table %s(key text,value text)", simpleTableNameString)->_string;
	createTable(simpleTableNameString, sqlstr);
}

//执行sql语句,示例以下:
//插入:insert into MyTable_1( name ) values ( '擎天柱' )
//删除:delete from MyTable_1 where ID = 2
//修改:update MyTable_1 set name='威震天' where ID = 3
void Sql::exec(std::string sql){
	result = sqlite3_exec(pDB,sql.c_str(),NULL,NULL,&errMsg);
	if (result!=SQLITE_OK){
		CCLOG("run sqlite fail:%s,code:%d,cause:%s\n",sql.c_str(),result,errMsg);
	}
	else{
		CCLOG("run sqlite success:%s",sql.c_str());
	}
}

//执行sql语句,有回调,通常用于查询语句
void Sql::exec(string sql, int(*callback)(void*, int, char**, char**), void* arg){
	result = sqlite3_exec(pDB, sql.c_str(), callback, arg, &errMsg);
	if (result != SQLITE_OK){
		CCLOG("run sqlite fail:%s,code:%d,cause:%s\n", sql.c_str(), result, errMsg);
	}
	else{
		CCLOG("run sqlite success:%s", sql.c_str());
	}
}

//关闭数据库
void Sql::close(){
	sqlite3_close(pDB);
}

//isTableExist的回调函数
int isExisted(void * para, int n_column, char ** column_value, char ** column_name)
{
	bool *isExisted_ = (bool*)para;
	*isExisted_ = (**column_value) != '0';
	return 0;
}
//该表是否存在
bool Sql::isTableExist(std::string tableName){
	if (pDB != NULL){
		//判断表是否存在
		bool isTableExist;
		sqlstr = "select count(type) from sqlite_master where type='table' and name ='" + tableName + "'";
		result = sqlite3_exec(pDB, sqlstr.c_str(), isExisted, &isTableExist, &errMsg);
		return isTableExist;
	}
	return false;
}

//建立一张表,若是已存在则不建立
//示例:create table user(id integer,username text,password text)
void Sql::createTable(std::string tableName, std::string sql){
	if (!isTableExist(tableName)){
		result = sqlite3_exec(pDB,sql.c_str(),NULL,NULL,&errMsg);
		if (result != SQLITE_OK){
			CCLOG("create sqlite table %s fail,code:%d,cause:%s\n",tableName,result,errMsg);
		}
		else{
			CCLOG("create sqlite table success:%s", tableName);
		}
	}
}

//删除一张表
bool Sql::deleteTable(std::string tableName){
	if (isTableExist(tableName)){//表存在的时候,执行删除语句
		sqlstr = "drop table " + tableName;
		result = sqlite3_exec(pDB,sqlstr.c_str(),NULL,NULL,&errMsg);
		if (result != SQLITE_OK){
			CCLOG("delete sqlite table %s fail,code:%d,cause:%s\n", tableName, result, errMsg);
			return false;
		}
	}
	return true;//能执行到最后,就说明删除成功了
}

int loadRecordCount(void* para, int n_col, char** col_value, char** col_name){
	int* count = (int*)para;
	*count = n_col;
	return 0;
}
//获取该表的行数
int Sql::getDataCount(std::string tableName){
	if (isTableExist(tableName)){
		sqlstr = "select count(*) from "+tableName;
		int count = 0;
		result = sqlite3_exec(pDB,sqlstr.c_str(),loadRecordCount,&count,&errMsg);
		if (result != SQLITE_OK){
			CCLOG("get sqlite table data count fail,code:%d,cause:%s\n", result, errMsg);
		}
		return count;
	}
	return 0;
}

//存int
void Sql::setInt(int key, int value){
	//先删除原先的数据
	sqlstr = String::createWithFormat("delete from %s where key=%d", simpleTableNameInt, key)->_string;
	exec(sqlstr);
	//再插入
	sqlstr = String::createWithFormat("insert into %s( key,value ) values ( %d,%d )",simpleTableNameInt,key,value)->_string;
	exec(sqlstr);
}
int loadRecordForInt(void * para, int n_column, char ** column_value, char ** column_name){
	int *value = (int*)para;
	*value = atoi(column_value[1]);
	return 0;
}
//取int
int Sql::getInt(int key, int defaultValue){
	int get = defaultValue;
	exec(String::createWithFormat("select * from %s where key=%d", simpleTableNameInt, key)->_string,loadRecordForInt,&get);
	return get;
}

//存string
void Sql::setString(std::string key, std::string value){
	//先删除原先的数据
	sqlstr = String::createWithFormat("delete from %s where key='%s'", simpleTableNameString, key.c_str())->_string;
	exec(sqlstr);
	//再插入
	sqlstr = String::createWithFormat("insert into %s( key,value ) values ( '%s','%s' )", simpleTableNameString, key.c_str(), value.c_str())->_string;
	exec(sqlstr);
}
int loadRecordForString(void * para, int n_column, char ** column_value, char ** column_name){
	string *value = (string*)para;
	*value = column_value[1];
	return 0;
}
//取string
string Sql::getString(string key, string defaultValue){
	string get = defaultValue;
	exec(String::createWithFormat("select * from %s where key='%s'", simpleTableNameString, key.c_str())->_string, loadRecordForString, &get);
	return get;
}