using UnityEngine;using System.Collections;using Mono.Data.Sqlite;using System.Data;using System.Collections.Generic;using System.IO;public class BaseSQLite {public static string dbPath = "mydatabase.sqlite"; //數據庫文件路徑 public static readonly string Path =#if UNITY_EDITOR string.Format("{0}",Application.streamingAssetsPath);#elif UNITY_ANDROID string.Format("jar:file://{0}!/assets", Application.dataPath);#endif //打開數據庫 public void OpenDB () {//如果當前數據庫處于關閉狀態則打開數據庫if (connection.State == ConnectionState.Closed) {connection.Open ();}}//執行增刪改指令public int Exec (string sqlStr, bool autoClose = true) {//打開數據庫OpenDB ();//給指令對象設置指令字符串command.CommandText = sqlStr;//執行指令int r = command.ExecuteNonQuery ();//如果設置了自動關閉數據庫if (autoClose) {//關閉數據庫CloseDB ();}//返回受到影響的數據行數return r;}//執行查詢指令public ArrayList Select (string sqlStr, bool autoClose = true) {//打開數據庫OpenDB ();//給指令對象設置指令字符串command.CommandText = sqlStr;//執行指令并獲取結果集讀取器SqliteDataReader reader = command.ExecuteReader ();//從結果集中獲取查詢結果并進行處理后返回//創建數組存儲查詢結果ArrayList dataArr = new ArrayList ();//使用循環每次處理一行結果while (reader.Read ()) {//創建字典存儲一行數據DictionaryrowDic = new Dictionary ();
// 使用循環每次處理一個字段的值
for (int i = 0;i < reader.FieldCount;i++) {
// 獲取當前字段名和值
string name = reader.GetName (i);
string value = reader.GetValue (i).ToString ();
// 將字段名和值作為 Key-Value 存儲在字典中
rowDic.Add (name, value);
}
// 將一行數據的字典存入數組
dataArr.Add (rowDic);
}
// 關閉結果集讀取器
reader.Close ();
// 如果設置了自動關閉數據庫
if (autoClose) {
// 關閉數據庫
CloseDB ();
}
// 返回查詢結果數組
return dataArr;
}
? ? public IDataReader DataReader(string sqlStr)
? ? {
? ? ? ? // 打開數據庫
? ? ? ? OpenDB();
? ? ? ? // 給指令對象設置指令字符串
? ? ? ? command.CommandText = sqlStr;
? ? ? ? // 執行指令并獲取結果集讀取器
? ? ? ? SqliteDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
? ? ? ? return reader;
? ? }
// 關閉數據庫
public void CloseDB () {
// 如果當前數據庫處于打開狀態則關閉數據庫
if (connection.State == ConnectionState.Open) {
connection.Close ();
}
}
// 獲取單例實例
public static BaseSQLite GetInstance () {
if (instance == null) {
instance = new BaseSQLite ();
}
return instance;
}
private static BaseSQLite instance = null; // 單例實例
private SqliteConnection connection = null; // 數據庫鏈接對象
private SqliteCommand command = null;? // 數據庫指令對象
? ? // 私有化默認構造
? ? private BaseSQLite()
? ? {
#if UNITY_EDITOR
? ? ? ? // 初始化數據庫鏈接對象
? ? ? ? connection = new SqliteConnection("Data Source = " + Path + "/" + dbPath);
#elif UNITY_ANDROID
? ? ? ? string appPath = Application.persistentDataPath + "/" + dbPath;
? ? ? ? if (!File.Exists(appPath))
? ? ? ? {
? ? ? ? ? ? WWW loadDB = new WWW(Path + "/" + dbPath);
? ? ? ? ? ? while (!loadDB.isDone){}
? ? ? ? ? ? File.WriteAllBytes(appPath, loadDB.bytes);
? ? ? ? }
? ? ? ? // 初始化數據庫鏈接對象? ? ?
? ? ? ? ? connection = new SqliteConnection("URI=file:" + appPath);
#endif
? ? ? ? //? ? ? ? // 初始化數據庫指令對象
? ? ? ? command = connection.CreateCommand ();
}
}