Unity技術(shù)博客 - Sqlite框架之美

Unity版本: 4.6

使用語言: C#


寫在前面

  項(xiàng)目開發(fā)中經(jīng)常會(huì)對數(shù)據(jù)庫進(jìn)行訪問和操作,很多人直接建一個(gè)腳本,在腳本中直接訪問數(shù)據(jù)庫!
  是的,對于數(shù)據(jù)庫的操作,我們應(yīng)該用一種更好的方式,讓代碼看上去更清晰。(耐心讀起來)

實(shí)現(xiàn)功能

  1. 創(chuàng)建數(shù)據(jù)架構(gòu),實(shí)現(xiàn)統(tǒng)一接口
  2. 簡單、清晰的訪問數(shù)據(jù)
  3. 跨平臺(tái)(手機(jī)、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ù)

數(shù)據(jù)庫建表(怪物表 ->主鍵ID 名字、血量、攻擊力、速度)

  • 2 在客戶端建立對應(yīng)的數(shù)據(jù)結(jié)構(gòu)表

using UnityEngine;
using System.Collections;
//所有數(shù)據(jù)結(jié)構(gòu)表的基類(核心)
//數(shù)據(jù)庫中每建一個(gè)表,就要在客戶端新建一個(gè)數(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;  //移動(dòng)速度

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";
//移動(dòng)端的數(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ù)不同平臺(tái),配置連接字符串
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)
{
//移動(dòng)端需要我們把數(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ù)(核心核心核心核心?。?br> 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)存放了怪物的信息
//我們可以在外面動(dòng)態(tài)改變怪物的類型
public MonsterType id = MonsterType.Wolf;
void Start()
{
    wolf = new Monster();
    #//這里很方便的實(shí)現(xiàn)了讀取數(shù)據(jù)
    DBManager.Instance.GetData<Monster>(wolf, (int)id);
    print (wolf.mName);
}
}

寫在最后

  當(dāng)你的程序越來越復(fù)雜的時(shí)候,框架的好處就會(huì)體現(xiàn)出來。
  #成功的道路沒有捷徑,代碼這條路更是如此,唯有敲才是王道。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、日志工具類L.java ``` package com.zhy.utils; import android.u...
    蠱惑007閱讀 1,074評(píng)論 1 1
  • 問題: 既然開始學(xué)習(xí)搭建SSH框架了,就必須對其3個(gè)框架起到的作用有一定的了解。 1.struts2------替...
    WBert閱讀 454評(píng)論 0 0
  • 自定義Mybatis的分析-執(zhí)行查詢所有分析查詢所有的分析.png 自定義Mybatis的分析-創(chuàng)建代理對象的分析...
    Deanfluenza01閱讀 350評(píng)論 0 0
  • 轉(zhuǎn)載請注明出處(http://www.itdecent.cn/p/5f538820e370),您的打賞是小編繼續(xù)...
    福later閱讀 29,699評(píng)論 8 73
  • 久違的晴天,家長會(huì)。 家長大會(huì)開好到教室時(shí),離放學(xué)已經(jīng)沒多少時(shí)間了。班主任說已經(jīng)安排了三個(gè)家長分享經(jīng)驗(yàn)。 放學(xué)鈴聲...
    飄雪兒5閱讀 7,810評(píng)論 16 22

友情鏈接更多精彩內(nèi)容