当前位置:   article > 正文

Unity Sqlite数据库操作_unitysqulite

unitysqulite

在Unity中使用sqlite的教程有很多。 包括:

研究院之使用C#语言建立本地数据库(二十三)

游戏开发之SQLite让数据库开发更简单

看完这两篇呢,基本上对sqlite数据库的使用都没有问题了,但是想在Unity中更方便的使用,我有对两者进行了改进和升级。


1.SqliteManager类

核心功能,使用C#函数,代替复杂的sql语句

 
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using Mono.Data.Sqlite;
  4. public class SqlManager : MonoSingleton{
  5. private const string dbName = "DBNAME";
  6. //链接数据库
  7. private SqliteConnection connection;
  8. //数据库命令
  9. private SqliteCommand command;
  10. //数据库阅读器
  11. private SqliteDataReader reader;
  12. //打开数据库
  13. public void OpenDB(string dbName)
  14. {
  15. try
  16. { //链接数据库操作
  17. string dbPath = Application.streamingAssetsPath + "/" + dbName + ".db";
  18. //固定sqlite格式data source
  19. connection = new SqliteConnection(@"Data Source = " + dbPath);
  20. connection.Open();
  21. Debug.Log("DataBase Connect");
  22. }
  23. catch (System.Exception e)
  24. {
  25. Debug.LogError(e.ToString());
  26. }
  27. }
  28. //关闭数据库
  29. public void CloseDB()
  30. {
  31. /*
  32. * IDispose接口可以通过Using(){}关键字实现使用后立刻销毁
  33. * Close ()方法回滚任何挂起的事务。然后,它将连接释放到连接池,或者在连接池被禁用的情况下关闭连接,
  34. * 应用程序可以多次调用 Close。不会生成任何异常。
  35. * Dispose()方法实际是和close()做的同一件事,唯一的区别是Dispose方法清空了connectionString,即设置为了null.
  36. */
  37. if (reader != null)
  38. reader.Close();
  39. if (command != null)
  40. command.Dispose();
  41. if (connection != null)
  42. connection.Close();
  43. Debug.Log("DataBase Close");
  44. }
  45. //创建数据库表
  46. public void CreateTabel(string _tableName,string[] col,string[] colType)
  47. {
  48. //string createSql = "CREATE TABLE player(ID int,name text,damage int)";
  49. if (col.Length != colType.Length)
  50. {
  51. Debug.LogError("Colum's Length != ColumType's Length");
  52. return;
  53. }
  54. string sql = "CREATE TABLE "+_tableName+"(";
  55. for(int i=0;i<col.Length;i++)
  56. {
  57. sql += col[i] + " " + colType[i] + ",";
  58. }
  59. sql = sql.TrimEnd(',');
  60. sql += ")";
  61. ExcuteSql(sql);
  62. }
  63. //插入数据
  64. public void Insert(string _tableName,object[] values)
  65. {
  66. //string createSql = "INSERT INTO player(ID,name,damage) VALUES (102,'ak47',120)";
  67. if (values.Length == 0)
  68. Debug.LogError("Values's length == 0");
  69. string sql = "INSERT INTO "+_tableName + " VALUES(";
  70. foreach(object value in values)
  71. {
  72. sql += "'" + value.ToString() + "'" +",";
  73. }
  74. sql = sql.TrimEnd(',');
  75. sql += ")";
  76. ExcuteSql(sql);
  77. }
  78. //删除数据 OR
  79. public void DeleteOR(string _tabelName, params object[] colums)
  80. {
  81. //string createSql = "delete from player where rowid=1";
  82. if (colums == null || colums.Length == 0)
  83. Debug.LogError("colums == null || colums.Length == 0");
  84. string sql = "DELETE FROM " + _tabelName + " WHERE ";
  85. for (int i = 0; i < colums.Length; i += 2)
  86. {
  87. sql += colums[i] + " = '" + colums[i + 1].ToString() + "' OR ";
  88. }
  89. sql = sql.Remove(sql.Length - 3);
  90. ExcuteSql(sql);
  91. }
  92. //删除数据 AND
  93. public void DeleteAND(string _tabelName, params object[] colums)
  94. {
  95. if (colums == null || colums.Length == 0)
  96. Debug.LogError("colums == null || colums.Length == 0");
  97. string sql = "DELETE FROM " + _tabelName + " WHERE ";
  98. for (int i=0;i<colums.Length;i+=2)
  99. {
  100. sql += colums[i] + " = '" + colums[i+1].ToString() + "' AND ";
  101. }
  102. sql = sql.Remove(sql.Length - 4);
  103. ExcuteSql(sql);
  104. }
  105. //更新数据 OR
  106. public void UpdateOR(string _tableNmae,object[] colums, params object[] options)
  107. {
  108. //string createSql = "Update player set name='M16' where id=102";
  109. if (colums == null || colums.Length == 0 || colums.Length % 2 == 1)
  110. Debug.LogError("colums Length has error!!!");
  111. if (options == null || options.Length == 0 || options.Length % 2 == 1)
  112. Debug.LogError("options Length has error!!!");
  113. string sql = "UPDATE " + _tableNmae + " SET ";
  114. for (int i = 0; i < colums.Length; i += 2)
  115. {
  116. sql += colums[i] + " = '" + colums[i + 1].ToString() + "' ";
  117. }
  118. sql += " WHERE ";
  119. for (int i = 0; i < options.Length; i+=2)
  120. {
  121. sql += options[i] + "=" + options[i+1].ToString() + " OR ";
  122. }
  123. sql = sql.Remove(sql.Length - 3);
  124. ExcuteSql(sql);
  125. }
  126. //更新数据 AND
  127. public void UpdateAND(string _tableNmae, object[] colums, params object[] options)
  128. {
  129. //string createSql = "Update player set name='M16' where id=102";
  130. if (colums == null || colums.Length == 0 || colums.Length % 2 == 1)
  131. Debug.LogError("colums Length has error!!!");
  132. if (options == null || options.Length == 0 || options.Length % 2 == 1)
  133. Debug.LogError("options Length has error!!!");
  134. string sql = "UPDATE " + _tableNmae + " SET ";
  135. for (int i = 0; i < colums.Length; i += 2)
  136. {
  137. sql += colums[i] + " = '" + colums[i + 1].ToString() + "' ";
  138. }
  139. sql += " WHERE ";
  140. for (int i = 0; i < options.Length; i += 2)
  141. {
  142. sql += options[i] + "=" + options[i + 1].ToString() + " AND ";
  143. }
  144. sql = sql.Remove(sql.Length - 4);
  145. ExcuteSql(sql);
  146. }
  147. //查询单个数据(ID是主键)
  148. public Dictionary<string, object> SelectByID(string _tableName,int Id)
  149. {
  150. string sql = "SELECT * FROM " + _tableName +" WHERE Id ="+Id;
  151. reader = ExcuteSql(sql);
  152. Dictionary<string, object> dic = new Dictionary<string, object>();
  153. //阅读电子书,翻页
  154. reader.Read();
  155. for (int i = 0; i < reader.FieldCount; i++)
  156. {
  157. dic.Add(reader.GetName(i), reader.GetValue(i));
  158. }
  159. reader.Close();
  160. return dic;
  161. }
  162. //查找所有
  163. public List<Dictionary<string, object>> SelectAll(string _tableName)
  164. {
  165. string sql = "SELECT * FROM " + _tableName;
  166. List<Dictionary<string, object>> dataArr = new List<Dictionary<string, object>>();
  167. reader = ExcuteSql(sql);
  168. while (reader.Read())
  169. {
  170. Dictionary<string, object> data = new Dictionary<string, object>();
  171. for (int i = 0; i < reader.FieldCount; i++)
  172. {
  173. string key = reader.GetName(i);
  174. object value = reader.GetValue(i);
  175. data.Add(key, value);
  176. }
  177. dataArr.Add(data);
  178. }
  179. return dataArr;
  180. }
  181. //按照自定义条件查找单条数据
  182. public Dictionary<string,object> SelectWithCondition(string _tableName,params object[] options)
  183. {
  184. if (options == null || options.Length == 0 || options.Length % 2 == 1)
  185. Debug.LogError("options Length has error!!!");
  186. string sql = "SELECT * FROM " + _tableName + " WHERE ";
  187. Dictionary<string, object> dic = new Dictionary<string, object>();
  188. for(int i=0;i< options.Length;i+=2)
  189. {
  190. sql += options[i] + "= '" + options[i + 1]+"' AND ";
  191. }
  192. sql = sql.Remove(sql.Length-4);
  193. reader = ExcuteSql(sql);
  194. reader.Read();
  195. for(int i=0;i<reader.FieldCount;i++)
  196. {
  197. string key = reader.GetName(i);
  198. object value = reader.GetValue(i);
  199. dic.Add(key, value);
  200. }
  201. return dic;
  202. }
  203. //按照自定义条件查找整张表数据
  204. public List<Dictionary<string, object>> SelectAllWithCondition(string _tableName, params object[] options)
  205. {
  206. if (options == null || options.Length == 0 || options.Length % 2 == 1)
  207. Debug.LogError("options Length has error!!!");
  208. string sql = "SELECT * FROM " + _tableName + " WHERE ";
  209. List<Dictionary<string, object>> dataArr = new List<Dictionary<string, object>>();
  210. for (int i = 0; i < options.Length; i += 2)
  211. {
  212. sql += options[i] + "= '" + options[i + 1] + "' AND ";
  213. }
  214. sql = sql.Remove(sql.Length - 4);
  215. reader = ExcuteSql(sql);
  216. while (reader.Read())
  217. {
  218. Dictionary<string, object> data = new Dictionary<string, object>();
  219. for (int i = 0; i < reader.FieldCount; i++)
  220. {
  221. string key = reader.GetName(i);
  222. object value = reader.GetValue(i);
  223. data.Add(key, value);
  224. }
  225. dataArr.Add(data);
  226. }
  227. return dataArr;
  228. }
  229. //执行数据库语句
  230. SqliteDataReader ExcuteSql(string _sql)
  231. {
  232. Debug.Log("Excuted Sql :" + _sql);
  233. //创建数据库连接命令(事务管理、命令管理:向数据库发送指令)
  234. command = connection.CreateCommand();
  235. //设置命令语句
  236. command.CommandText = _sql;
  237. //执行命令后 返回 阅读器信息
  238. using (reader = command.ExecuteReader())
  239. {
  240. return reader;
  241. }
  242. }
  243. }


2.实体类

数据库读出的数据,最终都是要转到实体类上的,一般两种方法:1.是手动转化,2.是通过反射自动赋值

这里为了方便起见,暂时使用了手动转化的方式。

代码如下:

  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. public class SqlDataBase
  4. {
  5. public virtual SqlDataBase InitWithSqlData(Dictionary<string, object> _data)
  6. {
  7. return null;
  8. }
  9. }
  10. public class Player : SqlDataBase
  11. {
  12. public int id;
  13. public string name;
  14. public int level;
  15. public int hp;
  16. public int ep;
  17. public int exp;
  18. //数据库中读出的字典数据->实体类
  19. public override SqlDataBase InitWithSqlData(Dictionary<string, object> data)
  20. {
  21. this.id = System.Convert.ToInt32(data["id"]);
  22. this.name = System.Convert.ToString(data["name"]);
  23. this.level = System.Convert.ToInt32(data["level"]);
  24. this.hp = System.Convert.ToInt32(data["hp"]);
  25. this.ep = System.Convert.ToInt32(data["ep"]);
  26. this.exp = System.Convert.ToInt32(data["exp"]);
  27. return this;
  28. }
  29. }

 

3.DAO类

现在数据库读取方法有了,数据库数据转实体类也有了,但是我现在想获取一个最简单的Player Id为1的数据,还是要写好几行代码。

因此一般开发当中,都需要一个DAO(Data Access Object)中间工具类DAO类,来帮助我们,说白了,DAO就是帮助我们通过一行代码获得我们想要的数据实体。

 
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. public class DAO<T> where T :SqlDataBase,new() {
  4. public static T GetById(int id)
  5. {
  6. return GetInfoWithCondition(typeof(T).Name, new object[] { "id", id });
  7. }
  8. public static List<T> GetAllInfos()
  9. {
  10. string tableName = typeof(T).ToString().ToLower();
  11. List<Dictionary<string, object>> resultList = SqlManager.Instance.SelectAll(tableName);
  12. if (resultList.Count == 0)
  13. {
  14. return default(List<T>);
  15. }
  16. List<T> t = new List<T>();
  17. for (int i = 0; i < resultList.Count; i++)
  18. {
  19. T tmp = new T();
  20. tmp.InitWithSqlData(resultList[i]);
  21. t.Add(tmp);
  22. }
  23. return t;
  24. }
  25. public static T GetInfoWithCondition(string tableName, object[] options)
  26. {
  27. UnityEngine.Assertions.Assert.IsTrue(options.Length % 2 == 0, "[DAO GetInfoFromTable] options error.");
  28. Dictionary<string, object> resultList = SqlManager.Instance.SelectWithCondition(tableName,options);
  29. T tmp = new T();
  30. tmp.InitWithSqlData(resultList);
  31. return tmp;
  32. }
  33. public static List<T> GetInfosWithCondition(string tableName, object[] options)
  34. {
  35. UnityEngine.Assertions.Assert.IsTrue(options.Length % 2 == 0, "[DAO GetInfoFromTable] options error.");
  36. List<Dictionary<string, object>> resultList = SqlManager.Instance.SelectAllWithCondition(tableName, options);
  37. if (resultList.Count == 0)
  38. {
  39. return default(List<T>);
  40. }
  41. List<T> t = new List<T>();
  42. for (int i = 0; i < resultList.Count; i++)
  43. {
  44. T tmp = new T();
  45. tmp.InitWithSqlData(resultList[i]);
  46. t.Add(tmp);
  47. }
  48. return t;
  49. }
  50. }


4.总结

那么经过上面的努力,现在我们想查询一个player或者player列表,就只需要一行代码

  1. //查询101玩家
  2. var p = DAO<Player>.GetById(101)
  3. //查询所有玩家
  4. var list = DAO<Player>.GetAllInfos()

 

希望这篇文章对你有所帮助!!!
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/127134
推荐阅读
相关标签
  

闽ICP备14008679号