Unity版本: 4.6
使用語言: C#
寫在前面
項目開發(fā)中經(jīng)常會對數(shù)據(jù)庫進行訪問和操作勋拟,很多人直接建一個腳本,在腳本中直接訪問數(shù)據(jù)庫冗恨!
是的,對于數(shù)據(jù)庫的操作且改,我們應(yīng)該用一種更好的方式,讓代碼看上去更清晰持舆。(耐心讀起來)
實現(xiàn)功能
1. 創(chuàng)建數(shù)據(jù)架構(gòu)色瘩,實現(xiàn)統(tǒng)一接口
2. 簡單、清晰的訪問數(shù)據(jù)
3. 跨平臺(手機逸寓、PC端通用)
基本架構(gòu)
1. 數(shù)據(jù)庫建表
2. 在客戶端建立對應(yīng)的數(shù)據(jù)結(jié)構(gòu)表(基石)
3. 創(chuàng)建數(shù)據(jù)庫管理類(可以訪問數(shù)據(jù)庫)
4. 封裝讀取數(shù)據(jù)的接口(核心)
1 在數(shù)據(jù)庫建表居兆,添加三條數(shù)據(jù)
2 在客戶端建立對應(yīng)的數(shù)據(jù)結(jié)構(gòu)表
using UnityEngine;
using System.Collections;
//所有數(shù)據(jù)結(jié)構(gòu)表的基類(核心)
//數(shù)據(jù)庫中每建一個表,就要在客戶端新建一個數(shù)據(jù)結(jié)構(gòu)
public abstract class DBData{
public int mID; //主鍵勋篓,規(guī)定所有的表結(jié)構(gòu)都要有此主鍵
#//此方法用來解析數(shù)據(jù)(很重要)
public abstract void Parse(string[] result);
}
//所有的結(jié)構(gòu)表都要跟數(shù)據(jù)庫的表名相同
public class Monster : DBData {
public string mName; //名字
public int mHP; //血量
public int mAtk; //攻擊力
public int mSpeed; //移動速度
public override void Parse (string[] result)
{
int index = 0;
mID = System.Convert.ToInt32(result[index++]);
mName = result[index++];
mAtk = System.Convert.ToInt32(result[index++]);
mSpeed = System.Convert.ToInt32(result[index++]);
}
}
3 創(chuàng)建數(shù)據(jù)庫管理類
//數(shù)據(jù)庫訪問配置類
public static class DBConfig
{
//PC端的數(shù)據(jù)配置路徑
public static string PC_FilePath = Application.streamingAssetsPath + "/LanOu.sqlite";
public static string PC_ConnPath = "Data Source = " + Application.streamingAssetsPath + "/LanOu.sqlite";
//移動端的數(shù)據(jù)配置路徑 (persistentDataPath--沙盒)
public static string Mobile_FilePath = Application.persistentDataPath + "/LanOu.sqlite";
public static string Mobile_ConnPath = "URI=file: " + Application.persistentDataPath + "/LanOu.sqlite";
public static string Mobile_StreamingPath = "jar:file://" + Application.dataPath + "!/assets/" + "LanOu.sqlite";
}
public class DBManager {
#region 單例
private DBManager(){
SetConnStr();
Debug.Log(connPath);
Debug.Log(filePath);
}
private static DBManager instance;
public static DBManager Instance {
get {
if(instance == null)
{
instance = new DBManager();
}
return instance;
}
}
#endregion
#region Params
private SqliteCommand comd;
private SqliteConnection conn;
private SqliteDataReader dataReader;
private static string connPath;
private static string filePath;
#endregion
#region Method
//根據(jù)不同平臺,配置連接字符串
private void SetConnStr()
{
#if UNITY_ANDROID
connPath = DBConfig.Mobile_ConnPath;
filePath = DBConfig.Mobile_FilePath;
#endif
#if UNITY_STANDALONE_WIN
connPath = DBConfig.PC_ConnPath;
filePath = DBConfig.PC_FilePath;
#endif
#if UNITY_STANDALONE_OSX
connPath = DBConfig.PC_ConnPath;
filePath = DBConfig.PC_FilePath;
#endif
}
//開啟數(shù)據(jù)庫
private void OpenDB()
{
if(conn == null)
{
//移動端需要我們把數(shù)據(jù)庫復(fù)制到沙盒中
if(!File.Exists(filePath))
{
WWW www = new WWW(DBConfig.Mobile_StreamingPath);
while(!www.isDone){}
File.WriteAllBytes(filePath, www.bytes);
}
conn = new SqliteConnection(connPath);
conn.Open();
}
if(comd == null)
{
comd = conn.CreateCommand();
}
}
//關(guān)閉數(shù)據(jù)庫
private void CloseDB()
{
if(conn != null)
{
conn.Close();
}
if(comd != null)
{
comd.Dispose();
}
}
#//封裝方法,根據(jù)主鍵 解析數(shù)據(jù)(核心核心核心核心0上怼)
public void GetData<T>(T data, int id) where T : DBData
{
string sqlStr = "select * from " + data.GetType().Name + " where id = " + id;
string[] result = Execute(sqlStr);
if(result != null)
{
data.Parse(result);
}
}
//執(zhí)行查詢操作,返回結(jié)果形式:字符串?dāng)?shù)組
public string[] Execute(string sqlStr)
{
try {
OpenDB();
comd.CommandText = sqlStr;
dataReader = comd.ExecuteReader();
string[] result = null;
while(dataReader.Read())
{
result = new string[dataReader.FieldCount];
for(int i = 0; i < dataReader.FieldCount; i++)
{
result[i] = dataReader.GetValue(i).ToString();
}
break;
}
CloseDB();
return result;
} catch (System.Exception ex) {
return null;
Debug.Log(ex.ToString());
}
}
#endregion
}
4 在客戶端訪問數(shù)據(jù)
//創(chuàng)建枚舉譬嚣,表示怪物分為三類
public enum MonsterType
{
Wolf = 0,
Tiger = 1,
Boss = 11
}
public class Test : MonoBehaviour {
public Monster wolf; //內(nèi)存放了怪物的信息
//我們可以在外面動態(tài)改變怪物的類型
public MonsterType id = MonsterType.Wolf;
void Start()
{
wolf = new Monster();
#//這里很方便的實現(xiàn)了讀取數(shù)據(jù)
DBManager.Instance.GetData<Monster>(wolf, (int)id);
print (wolf.mName);
}
}
寫在最后
當(dāng)你的程序越來越復(fù)雜的時候钢颂,框架的好處就會體現(xiàn)出來。
#成功的道路沒有捷徑拜银,代碼這條路更是如此殊鞭,唯有敲才是王道遭垛。