在Unity中使用sqlite的教程有很多。 包括:
研究院之使用C#语言建立本地数据库(二十三)
游戏开发之SQLite让数据库开发更简单
看完这两篇呢,基本上对sqlite数据库的使用都没有问题了,但是想在Unity中更方便的使用,我有对两者进行了改进和升级。
首先,先来看下基本的SqliteManager,对Sqlite的基本操作工具类:
using UnityEngine;
using System.Collections.Generic;
using Mono.Data.Sqlite;
public class SqlManager : MonoBehaviour {
private const string dbName = "QikuEdu";
//链接数据库
private SqliteConnection connection;
//数据库命令
private SqliteCommand command;
//数据库阅读器
private SqliteDataReader reader;
private static SqlManager _instance = null;
public static SqlManager Instance
{
get
{
if (_instance == null)
{
GameObject obj = new GameObject();
_instance = obj.AddComponent();
}
return _instance;
}
}
void Awake()
{
if(null == _instance){
_instance = this;
}else{
GameObject.Destroy(this);
return;
}
//初始化,打开数据库
OpenDB(dbName);
}
//public SqlManager() { }
必须有参数的构造方法
//public SqlManager(string dbName)
//{
// OpenDB(dbName);
//}
public void OpenDB(string dbName)
{
try
{ //链接数据库操作
string dbPath = Application.streamingAssetsPath + "/" + dbName + ".db";
//固定sqlite格式data source
connection = new SqliteConnection(@"Data Source = " + dbPath);
connection.Open();
Debug.Log("DataBase Connect");
}
catch (System.Exception e)
{
Debug.LogError(e.ToString());
}
}
public void CloseDB()
{
/*
* IDispose接口可以通过Using(){}关键字实现使用后立刻销毁
* Close ()方法回滚任何挂起的事务。然后,它将连接释放到连接池,或者在连接池被禁用的情况下关闭连接,
* 应用程序可以多次调用 Close。不会生成任何异常。
* Dispose()方法实际是和close()做的同一件事,唯一的区别是Dispose方法清空了connectionString,即设置为了null.
*/
if (reader != null)
reader.Close();
if (command != null)
command.Dispose();
if (connection != null)
connection.Close();
Debug.Log("DataBase Close");
}
//创建数据库表
public void CreateTabel(string _tableName,string[] col,string[] colType)
{
//string createSql = "CREATE TABLE player(ID int,name text,damage int)";
if (col.Length != colType.Length)
{
Debug.LogError("Colum's Length != ColumType's Length");
return;
}
string sql = "CREATE TABLE "+_tableName+"(";
for(int i=0;i> Select(string _tableName)
//{
// string sql = "SELECT * FROM "+ _tableName;
// reader = ExcuteSql(sql);
// List> dicArr = new List>();
// //阅读电子书,翻页
// while(reader.Read())
// {
// //Debug.Log(reader.GetInt32(0) + ":" + reader.GetString(1) + ":" + reader.GetInt32(2));
// //int idex2 = reader.GetOrdinal("rowid");
// Dictionary dic = new Dictionary();
// dic.Add("ID",reader.GetValue(reader.GetOrdinal("ID")));
// dic.Add("Name",reader.GetValue(reader.GetOrdinal("Name")));
// dic.Add("Damage",reader.GetValue(reader.GetOrdinal("Damage")));
// dicArr.Add(dic);
// }
// reader.Close();
// return dicArr;
//}
按照ID查询(ID是主键)
//public Dictionary SelectByID(string _tableName,int Id)
//{
// string sql = "SELECT * FROM " + _tableName +" WHERE Id ="+Id;
// reader = ExcuteSql(sql);
// Dictionary dic = new Dictionary();
// //阅读电子书,翻页
// reader.Read();
// for (int i = 0; i < reader.FieldCount; i++)
// {
// dic.Add(reader.GetName(i), reader.GetValue(i));
// }
// reader.Close();
// return dic;
//}
//查找所有
public List> SelectAll(string _tableName)
{
string sql = "SELECT * FROM " + _tableName;
List> dataArr = new List>();
reader = ExcuteSql(sql);
while (reader.Read())
{
Dictionary data = new Dictionary();
for (int i = 0; i < reader.FieldCount; i++)
{
string key = reader.GetName(i);
object value = reader.GetValue(i);
data.Add(key, value);
}
dataArr.Add(data);
}
return dataArr;
}
//按照自定义条件查找单条数据
public Dictionary SelectWithCondition(string _tableName,params object[] options)
{
if (options == null || options.Length == 0 || options.Length % 2 == 1)
Debug.LogError("options Length has error!!!");
string sql = "SELECT * FROM " + _tableName + " WHERE ";
Dictionary dic = new Dictionary();
for(int i=0;i< options.Length;i+=2)
{
sql += options[i] + "= '" + options[i + 1]+"' AND ";
}
sql = sql.Remove(sql.Length-4);
reader = ExcuteSql(sql);
reader.Read();
for(int i=0;i> SelectAllWithCondition(string _tableName, params object[] options)
{
if (options == null || options.Length == 0 || options.Length % 2 == 1)
Debug.LogError("options Length has error!!!");
string sql = "SELECT * FROM " + _tableName + " WHERE ";
List> dataArr = new List>();
for (int i = 0; i < options.Length; i += 2)
{
sql += options[i] + "= '" + options[i + 1] + "' AND ";
}
sql = sql.Remove(sql.Length - 4);
reader = ExcuteSql(sql);
while (reader.Read())
{
Dictionary data = new Dictionary();
for (int i = 0; i < reader.FieldCount; i++)
{
string key = reader.GetName(i);
object value = reader.GetValue(i);
data.Add(key, value);
}
dataArr.Add(data);
}
return dataArr;
}
//执行数据库语句
SqliteDataReader ExcuteSql(string _sql)
{
Debug.Log("Excuted Sql :" + _sql);
//创建数据库连接命令(事务管理、命令管理:向数据库发送指令)
command = connection.CreateCommand();
//设置命令语句
command.CommandText = _sql;
//执行命令后 返回 阅读器信息
using (reader = command.ExecuteReader())
{
return reader;
}
}
}
using UnityEngine;
using System.Collections.Generic;
public class SqlDataBase
{
public virtual SqlDataBase InitWithSqlData(Dictionary _data)
{
return null;
}
}
public class Weapons : SqlDataBase
{
public int id;
public string name;
public int damage;
public int level;
public int color;
public static Weapons Copy(Weapons other)
{
Weapons ret = new Weapons();
ret.id = other.id;
ret.name = other.name;
ret.damage = other.damage;
ret.level = other.level;
ret.color = other.color;
return ret;
}
public override SqlDataBase InitWithSqlData(Dictionary data)
{
this.id = System.Convert.ToInt32(data["id"]);
this.name = System.Convert.ToString(data["name"]);
this.damage = System.Convert.ToInt32(data["damage"]);
this.level = System.Convert.ToInt32(data["level"]);
this.color = System.Convert.ToInt32(data["color"]);
return this;
}
}
public class Player : SqlDataBase
{
public int id;
public string name;
public int level;
public int hp;
public int ep;
public int exp;
public static Player Copy(Player other)
{
Player ret = new Player();
ret.id = other.id;
ret.name = other.name;
ret.level = other.level;
ret.hp = other.hp;
ret.ep = other.ep;
ret.exp = other.exp;
return ret;
}
public override SqlDataBase InitWithSqlData(Dictionary data)
{
this.id = System.Convert.ToInt32(data["id"]);
this.name = System.Convert.ToString(data["name"]);
this.level = System.Convert.ToInt32(data["level"]);
this.hp = System.Convert.ToInt32(data["hp"]);
this.ep = System.Convert.ToInt32(data["ep"]);
this.exp = System.Convert.ToInt32(data["exp"]);
return this;
}
}
public class Enemy : SqlDataBase
{
public int id;
public string name;
public int level;
public int damage;
public int hp;
public int ep;
public int exp;
public static Enemy Copy(Enemy other)
{
Enemy ret = new Enemy();
ret.id = other.id;
ret.name = other.name;
ret.level = other.level;
ret.damage = other.damage;
ret.hp = other.hp;
ret.ep = other.ep;
ret.exp = other.exp;
return ret;
}
public override SqlDataBase InitWithSqlData(Dictionary data)
{
this.id = System.Convert.ToInt32(data["id"]);
this.name = System.Convert.ToString(data["name"]);
this.level = System.Convert.ToInt32(data["level"]);
this.damage = System.Convert.ToInt32(data["damage"]);
this.hp = System.Convert.ToInt32(data["hp"]);
this.ep = System.Convert.ToInt32(data["ep"]);
this.exp = System.Convert.ToInt32(data["exp"]);
return this;
}
}
using UnityEngine;
using System.Collections.Generic;
public class DAO where T :SqlDataBase,new() {
public static T GetById(int id)
{
return GetInfoWithCondition(typeof(T).Name, new object[] { "id", id });
}
public static List GetAllInfos()
{
string tableName = typeof(T).ToString().ToLower();
List> resultList = SqlManager.Instance.SelectAll(tableName);
if (resultList.Count == 0)
{
return default(List);
}
List t = new List();
for (int i = 0; i < resultList.Count; i++)
{
T tmp = new T();
tmp.InitWithSqlData(resultList[i]);
t.Add(tmp);
}
return t;
}
public static T GetInfoWithCondition(string tableName, object[] options)
{
UnityEngine.Assertions.Assert.IsTrue(options.Length % 2 == 0, "[DAO GetInfoFromTable] options error.");
Dictionary resultList = SqlManager.Instance.SelectWithCondition(tableName,options);
T tmp = new T();
tmp.InitWithSqlData(resultList);
return tmp;
}
public static List GetInfosWithCondition(string tableName, object[] options)
{
UnityEngine.Assertions.Assert.IsTrue(options.Length % 2 == 0, "[DAO GetInfoFromTable] options error.");
List> resultList = SqlManager.Instance.SelectAllWithCondition(tableName, options);
if (resultList.Count == 0)
{
return default(List);
}
List t = new List();
for (int i = 0; i < resultList.Count; i++)
{
T tmp = new T();
tmp.InitWithSqlData(resultList[i]);
t.Add(tmp);
}
return t;
}
}