Unity 使用SQLlite数据库(一)

前期准备工作可参考:https://blog.csdn.net/qq_37067895/article/details/85396269
https://blog.csdn.net/qinyuanpei/article/details/46812655

或者从下面链接中可获取DLL包工具

然后利用SQLLiteStudio,创建一个数据库

Unity 使用SQLlite数据库(一)_第1张图片

之后,把MyTestDB.dll导到unity项目中如下:

Unity 使用SQLlite数据库(一)_第2张图片

接下来,也把SQLlite三件套也导入unity项目中:

Unity 使用SQLlite数据库(一)_第3张图片

剩下的就是代码部分,

数据必要有的---增删查改,.这里先做个基类如下:

/*******************************************************************
* 作者:     # maki #
* 创建日期: #2019年9月5日17:02:49  #
* 描述:  数据库操作接口
******************************************************************/
using System.Collections.Generic;
using System.Data;

namespace DataBaseTool
{
    public interface IDataBase
    {
        /// 
        /// 打开数据库
        /// 
        /// 
        void Open(string sqlUrl);
        /// 
        /// 关闭数据库
        /// 
        void Close();
        /// 
        /// 开始使用事务,在停止使用事务前,通过ReplaceValues保存数据的SQL命令会集中起来,等待停止事务后一起执行命令
        /// 
        void StartTransaction();
        /// 
        /// 停止使用事务
        /// 
        void StopTransaction();
        /// 
        /// 检查数据表是否存在
        /// 
        /// 表名
        /// 
        bool CheckTableIsExist(string tableName);
        /// 
        /// 创建数据表
        /// 
        /// 
        /// 
        /// 
        void CreatTable(string tableName, string[] colNames, string[] colTypes);

        /// 
        /// 更新或者保存数据
        /// 
        /// 表名
        /// 字段名集合
        /// 数据集合
        /// 
        bool UpdateOrSave(string tableName, string[] colNames, object[] colValues);
        /// 
        /// 更新或者保存数据 - 针对集合数据
        /// 
        /// 表名
        /// 字段名集合
        /// 数据集合
        /// 
        bool UpdateOrSave(string tableName, List listColNames, List listColValues);
        /// 
        /// 删除符合任一条件的数据
        /// 
        /// 表名
        /// 字段名集合
        /// 比较符号集合
        /// 数据集合
        /// 
        bool DeleteAnyone(string tableName, string[] colNames, string[] operations, string[] colValues);
        /// 
        /// 删除符合所有条件的数据
        /// 
        /// 表名
        /// 字段名集合
        /// 比较符号集合
        /// 数据集合
        /// 
        bool DeleteEveryone(string tableName, string[] colNames, string[] operations, string[] colValues);
        /// 
        /// 获取符合任一条件的数据
        /// 
        /// 
        /// 表名
        /// 字段名集合
        /// 比较符号集合
        /// 数据集合
        /// 
        List GetAnyone(string tableName, string[] colNames, string[] operations, string[] colValues);
        /// 
        /// 获取符合全部条件的数据
        /// 
        /// 
        /// 表名
        /// 字段名集合
        /// 比较符号集合
        /// 数据集合
        /// 
        List GetEveryone(string tableName, string[] colNames, string[] operations, string[] colValues);
        /// 
        /// 获取该表所有数据
        /// 
        /// 
        /// 表名
        /// 
        List GetAll(string tableName);
        /// 
        /// 获取符合任一条件的某些字段的数据
        /// 
        /// 表名
        /// 需要获取数据的字段名集合
        /// 字段名集合
        /// 比较符号集合
        /// 数据集合
        /// 
        List> GetForAnyone(string tableName, string[] items, string[] colNames, string[] operations, string[] colValues);
        /// 
        /// 获取符合全部条件的某些字段的数据
        /// 
        /// 表名
        /// 需要获取数据的字段名集合
        /// 字段名集合
        /// 比较符号集合
        /// 数据集合
        /// 
        List> GetForEveryone(string tableName, string[] items, string[] colNames, string[] operations, string[] colValues);
        /// 
        /// 获取某数据表的所有字段
        /// 
        /// 表名
        /// 
        List GetTableAllFields(string tableName);
        /// 
        /// 获取所有数据表
        /// 
        /// 
        List GetAllTableName();
        /// 
        /// 获取表的相关信息
        /// 
        /// 表名
        /// 
        DataTable GetTableInfo(string tableName);
    }

}

之后,利用sqllite库写的管理类:

/*******************************************************************
* 作者:     # maki  #
* 创建日期: # 2019年9月5日17:18:52 #
* 描述:  sqllite 数据库管理类
******************************************************************/
using Mono.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using UnityEngine;

namespace DataBaseTool
{
    public class SqlLiteManager : IDataBase
    {

        /// 
        /// 数据库连接
        /// 
        private SqliteConnection dbConnection = null;

        /// 
        /// SQL命令
        /// 
        private SqliteCommand dbCommand = null;

        /// 
        /// 数据读取
        /// 
        private SqliteDataReader dataReader = null;

        private SqliteParameter myParameter;

        /// 
        /// 事务
        /// 
        private SqliteTransaction transaction;

        /// 
        /// 是否开始事务
        /// 
        private bool isStartUseTransaction;

        /// 
        /// 打开数据库
        /// 
        public void Open(string sqlUrl)
        {
            try
            {
                //构造数据库连接
                dbConnection = new SqliteConnection(sqlUrl);
                //打开数据库
                dbConnection.Open();
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);
            }
        }
        /// 
        /// 关闭数据库
        /// 
        public void Close()
        {
            //销毁Command
            if (dbCommand != null) dbCommand.Cancel();
            //销毁Reader
            if (dataReader != null) dataReader.Close();
            //销毁Connection
            if (dbConnection != null) dbConnection.Close();

            dbCommand = null;
            dataReader = null;
            dbConnection = null;
            Debug.Log("关闭数据库");
        }

        /// 
        /// 执行SQL命令
        /// 
        /// SQL命令字符串
        /// 
        public SqliteDataReader ExecuteQuery(string queryString)
        {
            dbCommand = dbConnection.CreateCommand();
            dbCommand.CommandText = queryString;
            dataReader = dbCommand.ExecuteReader();
            return dataReader;
        }
        /// 
        /// 执行SQL命令
        /// 
        /// SQL命令字符串
        /// SQL命令字符串
        /// 
        public void ExecuteQuery(string queryString, SqliteParameter[] content)
        {
            dbCommand = dbConnection.CreateCommand();
            dbCommand.CommandText = queryString;
            dbCommand.Parameters.AddRange(content);

            /**ExecuteNonQuery方法主要用来更新数据,
             * 当然也可以用来执行目标操作
             * (例如查询数据库的结构或者创建诸如表等的数据库对象)。
             * 通常用它来执行insert、update、delete语句,
             * 在不使用Dataset的情况下更改数据库中的数据。
             * select语句不适合ExecuteNonQuery()方法。
             * 文档地址:https://www.cnblogs.com/erhanhan/p/8270052.html
             * **/
            dbCommand.ExecuteNonQuery();
        }

        /// 
        /// 读取整张数据表
        /// 
        /// The full table.
        /// 数据表名称
        public SqliteDataReader ReadFullTable(string tableName)
        {
            string queryString = "SELECT * FROM " + tableName;
            return ExecuteQuery(queryString);
        }

        /****************************   事务操作   ************************************/

        /// 
        /// 开始使用事务,在停止使用事务前,通过ReplaceValues保存数据的SQL命令会集中起来,等待停止事务后一起执行命令
        /// 
        public void StartTransaction()
        {
            isStartUseTransaction = true;
            dbCommand = dbConnection.CreateCommand();
            transaction = dbConnection.BeginTransaction();
        }
        /// 
        /// 停止使用事务
        /// 
        public void StopTransaction()
        {
            isStartUseTransaction = false;
            transaction.Commit();
        }

        /****************************   对表操作   ************************************/

        /// 
        /// 检查数据表是否存在
        /// 
        public bool CheckTableIsExist(string tableName)
        {
            dbCommand = dbConnection.CreateCommand();
            dbCommand.CommandText = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='" + tableName + "';";
            if (0 == Convert.ToInt32(dbCommand.ExecuteScalar()))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// 
        /// 创建数据表
        /// 
        public void CreatTable(string tableName, string[] colNames, string[] colTypes)
        {
            string queryString = "CREATE TABLE " + tableName + "( " + colNames[0] + " " + colTypes[0];
            for (int i = 1; i < colNames.Length; i++)
            {
                queryString += ", " + colNames[i] + " " + colTypes[i];
            }
            queryString += "  ) ";
            ExecuteQuery(queryString);
        }

        /****************************   更新或者保存数据    ************************************/

        /// 
        /// 更新或者保存数据
        /// 
        public bool UpdateOrSave(string tableName, string[] colNames, object[] colValues)
        {
            try
            {
                string queryString = "REPLACE INTO " + tableName + "(" + colNames[0];
                for (int i = 1; i < colNames.Length; i++)
                {
                    queryString += "," + colNames[i];
                }

                queryString += ") VALUES (" + "@" + colNames[0];
                for (int j = 1; j < colNames.Length; j++)
                {
                    queryString += "," + "@" + colNames[j];
                }
                queryString += ")";

                SqliteParameter[] parameters = new SqliteParameter[colNames.Length];
                for (int k = 0; k < parameters.Length; k++)
                {
                    parameters[k] = new SqliteParameter("@" + colNames[k], colValues[k]);
                }

                if (isStartUseTransaction)
                {
                    // 累积SQL执行语句
                    dbCommand.CommandText = queryString;
                    dbCommand.Parameters.AddRange(parameters);
                    dbCommand.ExecuteNonQuery();
                }
                else
                {
                    ExecuteQuery(queryString, parameters);
                }
                return true;
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return false;
            }
        }
        /// 
        /// 更新或者保存数据
        /// 
        public bool UpdateOrSave(string tableName, List listColNames, List listColValues)
        {
            try
            {
                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();
                string[] colNames = listColNames[0];

                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("REPLACE INTO {0}({1}", tableName, colNames[0]);
                for (int i = 1; i < colNames.Length; i++)
                {
                    sb.Append(",").Append(colNames[i]);
                }

                sb.Append(") VALUES (@").Append(colNames[0]);
                for (int j = 1; j < colNames.Length; j++)
                {
                    sb.Append(",@").Append(colNames[j]); ;
                }
                sb.Append(")");

                dbCommand = dbConnection.CreateCommand();
                dbCommand.CommandText = sb.ToString();

                var transaction = dbConnection.BeginTransaction();
                SqliteParameter[] parameters;
                for (int i1 = 0; i1 < listColNames.Count; i1++)
                {
                    parameters = new SqliteParameter[colNames.Length];
                    for (int k = 0; k < parameters.Length; k++)
                    {
                        parameters[k] = new SqliteParameter("@" + colNames[k], listColValues[i1][k]);
                    }

                    dbCommand.Parameters.AddRange(parameters);
                    dbCommand.ExecuteNonQuery();
                }
                transaction.Commit();

                watch.Stop();
                Debug.Log(watch.Elapsed);
                return true;
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return false;
            }
        }

        /****************************  删除符合条件的数据    ************************************/

        /// 
        /// 删除符合任一条件的数据
        /// 
        public bool DeleteAnyone(string tableName, string[] colNames, string[] operations, string[] colValues)
        {
            try
            {
                //当字段名称和字段数值不对应时引发异常
                if (colNames.Length != colValues.Length || operations.Length != colNames.Length || operations.Length != colValues.Length)
                {
                    throw new SqliteException("colNames.Length!=colValues.Length || operations.Length!=colNames.Length || operations.Length!=colValues.Length");
                }

                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("DELETE FROM {0} WHERE {1}{2}'{3}'", tableName, colNames[0], operations[0], colValues[0]);
                for (int i = 1; i < colValues.Length; i++)
                {
                    sb.AppendFormat("OR {0}{1}'{2}'", colNames[i], operations[i], colValues[i]);
                }

                ExecuteQuery(sb.ToString());
                return true;
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return false;
            }
        }
        /// 
        /// 删除符合所有条件的数据
        /// 
        public bool DeleteEveryone(string tableName, string[] colNames, string[] operations, string[] colValues)
        {
            try
            {
                //当字段名称和字段数值不对应时引发异常
                if (colNames.Length != colValues.Length || operations.Length != colNames.Length || operations.Length != colValues.Length)
                {
                    throw new SqliteException("colNames.Length!=colValues.Length || operations.Length!=colNames.Length || operations.Length!=colValues.Length");
                }

                string queryString = "DELETE FROM " + tableName + " WHERE " + colNames[0] + operations[0] + "'" + colValues[0] + "'";
                for (int i = 1; i < colValues.Length; i++)
                {
                    queryString += " AND " + colNames[i] + operations[i] + "'" + colValues[i] + "'";
                }
                ExecuteQuery(queryString);
                return true;
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return false;
            }
        }

        /****************************  获取该表数据    ************************************/

        /// 
        /// 获取该表所有数据
        /// 
        public List GetAll(string tableName)
        {
            string queryString = "SELECT * FROM " + tableName;
            return GetValues(queryString);
        }
        /// 
        /// 获取符合任一条件的数据
        /// 
        public List GetAnyone(string tableName, string[] colNames, string[] operations, string[] colValues)
        {
            try
            {
                string queryString = "SELECT * FROM " + tableName + " WHERE " + colNames[0] + operations[0] + "'" + colValues[0] + "'";
                for (int i = 1; i < colNames.Length; i++)
                {
                    queryString += " OR " + colNames[i] + operations[i] + "'" + colValues[i] + "'";
                }
                return GetValues(queryString);
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return new List();
            }
        }
        /// 
        /// 获取符合全部条件的数据
        ///  GetEveryone(string tableName, string[] colNames, string[] operations, string[] colValues)
        {
            try
            {
                string queryString = "SELECT * FROM " + tableName + " WHERE " + colNames[0] + operations[0] + "'" + colValues[0] + "'";
                for (int i = 1; i < colNames.Length; i++)
                {
                    queryString += " AND " + colNames[i] + operations[i] + "'" + colValues[i] + "'";
                }
                return GetValues(queryString);
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return new List();
            }
        }
        /// 
        /// 获取符合任一条件的某些字段的数据
        /// 
        public List> GetForAnyone(string tableName, string[] items, string[] colNames, string[] operations, string[] colValues)
        {
            try
            {
                string queryString = "SELECT " + items[0];
                for (int i = 1; i < items.Length; i++)
                {
                    queryString += ", " + items[i];
                }
                queryString += " FROM " + tableName + " WHERE " + colNames[0] + operations[0] + "'" + colValues[0] + "'";
                for (int i = 0; i < colNames.Length; i++)
                {
                    queryString += " OR " + colNames[i] + operations[i] + "'" + colValues[i] + "'";
                }

                return GetValuesForItems(queryString, items);
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return new List>();
            }
        }
        /// 
        /// 获取符合全部条件的某些字段的数据
        /// 
        public List> GetForEveryone(string tableName, string[] items, string[] colNames, string[] operations, string[] colValues)
        {
            try
            {
                string queryString = "SELECT " + items[0];
                for (int i = 1; i < items.Length; i++)
                {
                    queryString += ", " + items[i];
                }
                queryString += " FROM " + tableName + " WHERE " + colNames[0] + operations[0] + "'" + colValues[0] + "'";
                for (int i = 0; i < colNames.Length; i++)
                {
                    queryString += " AND " + colNames[i] + operations[i] + "'" + colValues[i] + ",";
                }

                return GetValuesForItems(queryString, items);
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return new List>();
            }
        }

        /****************************  获取表,名 相关数据    ************************************/

        /// 
        /// 获取某数据表的所有字段名
        /// 
        public List GetTableAllFields(string tableName)
        {
            string queryString = "Pragma Table_Info(" + tableName + ")";

            List listFields = new List();
            try
            {
                ExecuteQuery(queryString);

                while (dataReader.Read())
                {
                    listFields.Add(dataReader["Name"].ToString());
                }

                return listFields;
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return listFields;
            }
        }
        /// 
        /// 获取所有数据表名
        /// 
        public List GetAllTableName()
        {
            string queryString = "select name from sqlite_master where type= 'table' order by name";

            List list = new List();
            try
            {
                ExecuteQuery(queryString);

                while (dataReader.Read())
                {
                    list.Add(dataReader["Name"].ToString());
                }

                return list;
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return list;
            }
        }
        /// 
        /// 获取表的相关信息
        /// 
        public DataTable GetTableInfo(string tableName)
        {
            DataTable dt = new DataTable();
            try
            {
                ReadFullTable(tableName);
                dt = dataReader.GetSchemaTable();
                return dt;
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return dt;
            }
        }

        /****************************  其他处理数据    ************************************/

        /// 
        /// 通过SQL语句获取数据
        /// 
        /// 
        /// 获取数据方式
        /// 
        private List GetValues(string queryString)
        {
            try
            {
                List fields = GetTableAllFields(typeof(T).Name);
                ExecuteQuery(queryString);

                PropertyInfo[] pros = typeof(T).GetProperties();
                List listT = new List();
                while (dataReader.Read())
                {
                    T t = Activator.CreateInstance();
                    foreach (PropertyInfo item in pros)
                    {
                        //如果数据表不包含该字段,不读取
                        if (!fields.Contains(item.Name))
                            continue;

                        var result = dataReader.GetValue(dataReader.GetOrdinal(item.Name));
                        if (!string.IsNullOrEmpty(result.ToString()))
                        {
                            item.SetValue(t, Convert.ChangeType(result, item.PropertyType), null);
                        }
                    }
                    listT.Add(t);
                }
                return listT;
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return new List();
            }
        }
        /// 
        /// 获取指定的某些字段数据
        /// 
        /// SQL语句
        /// 要获取的字段
        /// 
        private List> GetValuesForItems(string queryString, string[] items)
        {
            try
            {
                ExecuteQuery(queryString);

                List> list = new List>();
                for (int i = 0; i < items.Length; i++)
                {
                    List listTemp = new List();
                    list.Add(listTemp);
                }

                while (dataReader.Read())
                {
                    for (int i = 0; i < items.Length; i++)
                    {
                        var result = dataReader.GetValue(dataReader.GetOrdinal(items[i]));
                        list[i].Add(result);
                    }
                }
                return list;
            }
            catch (Exception e)
            {
                Debug.Log(e);
                return new List>();
            }
        }
    }
}
 
  

最后是写个可以调用的帮助类

/*******************************************************************
* 作者:     # maki #
* 创建日期: # 2019年9月5日18:05:56 #
* 描述: 数据库  SqlBase的帮助类  单例模式
******************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using UnityEngine;

namespace DataBaseTool
{
    public class DataBaseHelper
    {
        private DataBaseHelper() { }
        private static DataBaseHelper instance;
        //单例
        public static DataBaseHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new DataBaseHelper();
                }
                return instance;
            }
        }

        private IDataBase dbBase;

        /// 
        /// 初始化数据库
        /// 
        /// 用的是哪种数据库
        public void Init(IDataBase dbBase, string loginSql)
        {
            this.dbBase = dbBase;
            this.dbBase.Open(loginSql);
        }
        /// 
        /// 关闭数据库
        /// 
        public void CloseDB()
        {
            if (dbBase != null)dbBase.Close();
        }

        /****************************   对表操作   ************************************/

        /// 
        /// 检查数据库里是否存在数据表
        /// 
        /// 表名
        /// 
        public bool CheckTableIsExist(string tableName)
        {
            if (dbBase.CheckTableIsExist(tableName))
            {
                return true;
            }
            Debug.Log("该类型对应的数据表不存在" + tableName);
            return false;
        }

        /// 
        /// 创建一个表
        /// 
        /// 
        /// 字段名
        /// 运算符
        /// 结果
        /// 
        public bool CreatTable(T t)
        {
            string tableName = typeof(T).Name;
            if (CheckTableIsExist(tableName))
            {
                Debug.Log(tableName);
                return false;
            }

            PropertyInfo[] pros = typeof(T).GetProperties();
            //要修改的字段集合
            List colNames = new List();
            //对应的内容
            List colTypes = new List();

            for (int i = 0; i < pros.Length; i++)
            {
                //判断属性的特性,具有某些特性的特殊处理
                object[] ob = pros[i].GetCustomAttributes(typeof(PropertySign), true);
                PropertyType proType = PropertyType.None;
                if (ob.Length > 0)
                    proType = ((PropertySign)ob[0]).fieldType;

                //如果属性特性为不存在数据库里,则跳过当前循环
                if (proType == PropertyType.NotInDataBase)
                    continue;

                //如果属性特性为不存在数据库里,则跳过当前循环
                if (proType == PropertyType.PrimaryKeyInDataBase)
                    continue;

                colNames.Add(pros[i].Name);
                var result = pros[i].PropertyType.Name;Debug.Log(result);
                colTypes.Add(result);
            }
            CreatTable(tableName, colNames.ToArray(), colTypes.ToArray());
            return true;
        }

        /// 
        /// 创建一个表
        /// 
        /// 
        /// 字段名
        /// 运算符
        /// 结果
        /// 
        public void CreatTable(string tableName, string[] colNames, string[] colTypes)
        {
            dbBase.CreatTable(tableName, colNames, colTypes);
        }
        /****************************   保存或者更新   ************************************/

        /// 
        /// 保存或者更新数据,数据库会判断ID是否已存在,存在则更新数据,不存在则插入数据
        /// 
        /// 数据类型
        /// 插入的数据实体
        /// 
        public bool SaveOrUpdate(T t)
        {
            string tableName = typeof(T).Name;
            if (!CheckTableIsExist(tableName))
            {
                Debug.Log(tableName);
                return false;
            }

            PropertyInfo[] pros = typeof(T).GetProperties();
            //要修改的字段集合
            List colNames = new List();
            //对应的内容
            List colValues = new List();

            for (int i = 0; i < pros.Length; i++)
            {
                //判断属性的特性,具有某些特性的特殊处理
                object[] ob = pros[i].GetCustomAttributes(typeof(PropertySign), true);
                PropertyType proType = PropertyType.None;
                if (ob.Length > 0)
                    proType = ((PropertySign)ob[0]).fieldType;

                //如果属性特性为不存在数据库里,则跳过当前循环
                if (proType == PropertyType.NotInDataBase)
                    continue;

                //如果属性特性为不存在数据库里,则跳过当前循环
                if (proType == PropertyType.PrimaryKeyInDataBase)
                    continue;

                colNames.Add(pros[i].Name);
                var result = pros[i].GetValue(t, null);
                colValues.Add(result);
            }
            return dbBase.UpdateOrSave(tableName, colNames.ToArray(), colValues.ToArray());
        }

        /// 
        /// 保存或者更新数据,数据库会判断ID是否已存在,存在则更新数据,不存在则插入数据
        /// 
        /// 数据类型
        /// 插入的数据实体集合
        /// 
        public bool SaveOrUpdate(List tList)
        {
            string tableName = typeof(T).Name;
            if (!CheckTableIsExist(tableName))
            {
                return false;
            }

            PropertyInfo[] pros = typeof(T).GetProperties();

            List listColNames = new List();
            List listColValues = new List();

            foreach (var t in tList)
            {
                //要修改的字段集合
                List colNames = new List();
                //对应的内容
                List colValues = new List();

                for (int i = 0; i < pros.Length; i++)
                {
                    //判断属性的特性,具有某些特性的特殊处理
                    object[] ob = pros[i].GetCustomAttributes(typeof(PropertySign), true);
                    PropertyType proType = PropertyType.None;
                    if (ob.Length > 0)
                        proType = ((PropertySign)ob[0]).fieldType;

                    //如果属性特性为不存在数据库里,则跳过当前循环
                    if (proType == PropertyType.NotInDataBase)
                        continue;

                    //如果属性特性为不存在数据库里,则跳过当前循环
                    if (proType == PropertyType.PrimaryKeyInDataBase)
                        continue;

                    colNames.Add(pros[i].Name);
                    var result = pros[i].GetValue(t, null);
                    colValues.Add(result);
                }

                listColNames.Add(colNames.ToArray());
                listColValues.Add(colValues.ToArray());
            }

            return dbBase.UpdateOrSave(tableName, listColNames, listColValues);
        }


        /****************************   删除  ************************************/

        /// 
        /// 删除指定UUID的数据
        /// 
        /// 
        /// 唯一标识符
        /// 
        public bool DeleteById(string id)
        {
            string tableName = typeof(T).Name;
            if (!CheckTableIsExist(tableName))
            {
                return false;
            }
            return dbBase.DeleteAnyone(tableName, new string[] { "id" }, new string[] { "=" }, new string[] { id });
        }
        /// 
        /// 删除符合条件的数据
        /// 
        /// 
        /// 唯一标识符
        /// 
        public bool DeleteByCondition(string colName, string operation, string colValue)
        {
            string tableName = typeof(T).Name;
            if (!CheckTableIsExist(tableName))
            {
                return false;
            }
            return dbBase.DeleteAnyone(tableName, new string[] { colName }, new string[] { operation }, new string[] { colValue });
        }


        /****************************   获取  ************************************/

        /// 
        /// 获取符合一个条件的对应一条数据
        /// 
        /// 
        /// 字段名
        /// 运算符
        /// 结果
        /// 
        public T GetEveryone(string colName, string operation, string colValue)
        {
            string[] colNames = new string[] { colName };
            string[] operations = new string[] { operation };
            string[] colValues = new string[] { colValue };

            var list = GetEveryone(colNames, operations, colValues);
            if (list.Count > 0)
                return GetEveryone(colNames, operations, colValues)[0];
            else
                return default(T);
        }

        / 
        / 获取符合一个条件的对应数据
        / 
        / 
        / 字段名
        / 运算符
        / 结果
        / 
        //public List GetEveryone(string colName, string operation, string colValue)
        //{
        //    string[] colNames = new string[] { colName };
        //    string[] operations = new string[] { operation };
        //    string[] colValues = new string[] { colValue };

        //    return GetEveryone(colNames, operations, colValues);
        //}

        /// 
        /// 获取符合全部条件的数据
        /// 
        /// 
        /// 字段名
        /// 运算符
        /// 结果
        /// 
        public List GetEveryone(string[] colNames, string[] operations, string[] colValues)
        {
            string tableName = typeof(T).Name;
            if (!CheckTableIsExist(tableName))
            {
                return default(List);
            }
            return dbBase.GetEveryone(tableName, colNames, operations, colValues);
        }

        /// 
        /// 获取符合任一条件的数据
        /// 
        /// 
        /// 字段名
        /// 运算符
        /// 结果
        /// 
        public List GetAnyone(string[] colNames, string[] operations, string[] colValues)
        {
            string tableName = typeof(T).Name;
            if (!CheckTableIsExist(tableName))
            {
                return default(List);
            }
            return dbBase.GetAnyone(tableName, colNames, operations, colValues);
        }

        /// 
        /// 获取一张表的所有数据
        /// 
        /// 
        /// 
        public List GetAll()
        {
            string tableName = typeof(T).Name;
            if (!CheckTableIsExist(tableName))
            {
                return null;
            }
            return dbBase.GetAll(tableName);
        }

        /// 
        /// 获取指定的字段数据
        /// 
        /// 表名
        /// 要获取的字段数据
        /// 字段名
        /// 运算符
        /// 对应数据
        /// 
        public List GetValuesForItem(string item, string colName, string operation, string colValue)
        {
            string[] items = new string[] { item };
            string[] colNames = new string[] { colName };
            string[] operations = new string[] { operation };
            string[] colValues = new string[] { colValue };

            return GetForEveryone(items, colNames, operations, colValues)[0];
        }

        /// 
        /// 获取符合所有条件的指定的某些字段数据
        /// 
        /// 表名
        /// 要获取的字段数据
        /// 字段名
        /// 运算符
        /// 对应数据
        /// 
        public List> GetForEveryone(string[] items, string[] colNames, string[] operations, string[] colValues)
        {
            string tableName = typeof(T).Name;
            if (!CheckTableIsExist(tableName))
            {
                return null;
            }

            return dbBase.GetForEveryone(tableName, items, colNames, operations, colValues);
        }

        /// 
        /// 获取符合任一条件的指定的某些字段数据
        /// 
        /// 表名
        /// 要获取的字段数据
        /// 字段名
        /// 运算符
        /// 对应数据
        /// 
        public List> GetForAnyone(string[] items, string[] colNames, string[] operations, string[] colValues)
        {
            string tableName = typeof(T).Name;
            if (!CheckTableIsExist(tableName))
            {
                return null;
            }

            return dbBase.GetForAnyone(tableName, items, colNames, operations, colValues);
        }
        /****************************  获取表,名 相关数据    ************************************/

        /// 
        /// 获取数据库所有表的名字
        /// 
        /// 
        public List GetAllTableName()
        {
            return dbBase.GetAllTableName();
        }

        /// 
        /// 获取数据表的字段和字段类型
        /// 
        /// 
        /// 
        public DataTable GetTableInfo(string tableName)
        {
            if (!CheckTableIsExist(tableName))
            {
                return null;
            }

            return dbBase.GetTableInfo(tableName);
        }
    }
}

 
  

这样的话,全部实现SQLlite的调用

然后,我们再写个测试类,看看效果

/*******************************************************************
* 作者:     # maki #
* 创建日期: # 2019年9月6日12:24:26 #
* 描述:  测试连接sqllite数据库
* 
* TODO:我用代码创建的表/数据在studio里面不显示,我在studio里面创建的表,在代码中添加数据,也不显示
* 
******************************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DataBaseTool;
using System;

public class SqlLiteTest : MonoBehaviour {
   
    private DataBaseHelper dbHelper;
    // Use this for initialization
    void Start () {
        string path = Application.streamingAssetsPath + "MyTest.db3";
        string url = "data source =" + path;
        dbHelper = DataBaseHelper.Instance;
        dbHelper.Init(new SqlLiteManager(), url);


        Student stu = new Student()
        {
            id = Guid.NewGuid().ToString(),
            name = "mmm",
            age = 22,
            grade = "七十一班",
            score = 32.5f,
        };

        ///**获取所有表名**/
        //var names = dbHelper.GetAllTableName(); Debug.Log(names.Count);
        //names.ForEach(u => Debug.Log(u));

        //   /**创建一个表**/

        //   var bo = dbHelper.CreatTable(stu);
        //   /**添加数据**/
          dbHelper.SaveOrUpdate(stu);
        //   /**获取数据**/
        var s = dbHelper.GetAll();
        Debug.Log(s.Count);


        //var m = dbHelper.GetAll(); Debug.Log(m.Count);
    }

    // Update is called once per frame
    void Update () {
		
	}
}
public class Student
{
    public string id { get; set; }
    public string name { get; set; }
    public int age { get; set; }
    public string grade { get; set; }
    public float score { get; set; }
}

 

你可能感兴趣的:(Unity)