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 ();
}
}