当前位置:   article > 正文

unity中使用SQLite_unity sqlite

unity sqlite

一、准备

在Unity中使用SQLite数据库需要先导入三个dll文件,mono.data.sqlite.dll,System.data.dll,sqlite3.dll,到Assets/Plugins文件夹中。

mono.data.sqlite.dll和System.data.dll在Unity\Editor\Data\MonoBleedingEdge\lib\mono\2.0

sqlite3.dll需要下载:SQLite Download Page

window电脑下载:Precompiled Binaries for Windows(注意32位和64位);

二、代码

  1. using Mono.Data.Sqlite;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. public class DBManager : MonoBehaviour
  7. {
  8. private static DBManager _dbInstance = null;
  9. public static DBManager _DBInstance()
  10. {
  11. return _dbInstance;
  12. }
  13. private string dbName = "data"; //数据库名称
  14. //建立数据库连接
  15. SqliteConnection connection;
  16. //数据库命令
  17. SqliteCommand command;
  18. //数据库阅读器
  19. SqliteDataReader reader;
  20. private void Awake()
  21. {
  22. //连接数据库
  23. OpenConnect();
  24. }
  25. private void OnDestroy()
  26. {
  27. //断开数据库连接
  28. CloseDB();
  29. }
  30. void Start()
  31. {
  32. 创建表
  33. //string[] colNames = new string[] { "name", "password" };
  34. //string[] colTypes = new string[] { "string", "string" };
  35. //CreateTable("user", colNames, colTypes);
  36. 使用泛型创建数据表
  37. //CreateTable<T4>();
  38. 根据条件查找特定的字段
  39. //foreach (var item in SelectData("user", new string[] { "name" }, new string[] { "password", "123456" }))
  40. //{
  41. // Debug.Log(item);
  42. //}
  43. 更新数据
  44. //UpdataData("user", new string[] {"name", "yyy"}, new string[] { "name" ,"wxy" });
  45. 删除数据
  46. //DeleteValues("user", new string[] { "name","wxyqq" });
  47. 查询数据
  48. //foreach (var item in GetDataBySqlQuery("T4", new string[] { "name" }))
  49. //{
  50. // Debug.Log(item);
  51. //}
  52. foreach (var item in GetDataBySqlQuery("user",new string[] { "name"}))
  53. {
  54. Debug.Log(item);
  55. }
  56. 插入数据
  57. //string[] values = new string[] { "3", "33", "333" };
  58. //InsertValues("T4", values);
  59. 使用泛型插入对象
  60. //T4 t = new T4(2, "22", "222");
  61. //Insert<T4>(t);
  62. }
  63. /// <summary>
  64. /// 删除表
  65. /// </summary>
  66. /// <param name="tableName"></param>
  67. /// <returns></returns>
  68. public SqliteDataReader DeleteTable(string tableName)
  69. {
  70. string sql = "DROP TABLE " + tableName;
  71. return ExecuteQuery(sql);
  72. }
  73. /// <summary>
  74. /// 查询整张表的数据
  75. /// </summary>
  76. /// <param name="tableName"></param>
  77. /// <returns></returns>
  78. public SqliteDataReader SelectFullTableData(string tableName)
  79. {
  80. string queryString = "select * from " + tableName;
  81. return ExecuteQuery(queryString);
  82. }
  83. /// <summary>
  84. /// 查询数据
  85. /// </summary>
  86. /// <param name="tableName">表名</param>
  87. /// <param name="fields">需要查找数据</param>
  88. /// <returns></returns>
  89. public List<String> GetDataBySqlQuery(string tableName, string[] fields)
  90. {
  91. //string queryString = "select " + fields[0];
  92. //for (int i = 1; i < fields.Length; i++)
  93. //{
  94. // queryString += " , " + fields[i];
  95. //}
  96. //queryString += " from " + tableName;
  97. //return ExecuteQuery(queryString);
  98. List<string> list = new List<string>();
  99. string queryString = "SELECT * FROM " + tableName;
  100. reader = ExecuteQuery(queryString);
  101. while (reader.Read())
  102. {
  103. for (int i = 0; i < reader.FieldCount; i++)
  104. {
  105. object obj = reader.GetValue(i);
  106. list.Add(obj.ToString());
  107. }
  108. }
  109. return list;
  110. }
  111. /// <summary>
  112. /// 查询数据
  113. /// </summary>
  114. /// <param name="tableName">数据表名</param>
  115. /// <param name="values">需要查询的数据</param>
  116. /// <param name="fields">查询的条件</param>
  117. /// <returns></returns>
  118. public SqliteDataReader SelectData(string tableName, string[] values, string[] fields)
  119. {
  120. string sql = "select " + values[0];
  121. for (int i = 1; i < values.Length; i++)
  122. {
  123. sql += " , " + values[i];
  124. }
  125. sql += " from " + tableName + " where( ";
  126. for (int i = 0; i < fields.Length - 1; i += 2)
  127. {
  128. sql += fields[i] + " =' " + fields[i + 1] + " 'and ";
  129. }
  130. sql = sql.Substring(0, sql.Length - 4) + ");";
  131. return ExecuteQuery(sql);
  132. //用于查看打印
  133. //List<string> list = new List<string>();
  134. //reader = ExecuteQuery(sql);
  135. //for (int i = 0; i < reader.FieldCount; i++)
  136. //{
  137. // object obj = reader.GetValue(i);
  138. // list.Add(obj.ToString());
  139. //}
  140. //return list;
  141. }
  142. /// <summary>
  143. /// 执行SQL命令
  144. /// </summary>
  145. /// <param name="queryString">SQL命令字符串</param>
  146. /// <returns></returns>
  147. public SqliteDataReader ExecuteQuery(string queryString)
  148. {
  149. command = connection.CreateCommand();
  150. command.CommandText = queryString;
  151. reader = command.ExecuteReader();
  152. return reader;
  153. }
  154. /// <summary>
  155. /// 创建表(使用泛型)
  156. /// </summary>
  157. /// <typeparam name="T"></typeparam>
  158. public void CreateTable<T>()
  159. {
  160. var type = typeof(T);
  161. string sql = "create Table " + type.Name + "( ";
  162. var fields = type.GetFields();
  163. for (int i = 0; i < fields.Length; i++)
  164. {
  165. sql += " " + fields[i].Name + " " + CS2DB(fields[i].FieldType) + ",";
  166. }
  167. sql = sql.TrimEnd(',') + ")";
  168. ExecuteQuery(sql);
  169. }
  170. /// <summary>
  171. /// CS转化为DB类别
  172. /// </summary>
  173. /// <param name="type">c#中字段的类别</param>
  174. /// <returns></returns>
  175. string CS2DB(Type type)
  176. {
  177. string result = "Text";
  178. if (type == typeof(Int32))
  179. {
  180. result = "Int";
  181. }
  182. else if (type == typeof(String))
  183. {
  184. result = "Text";
  185. }
  186. else if (type == typeof(Single))
  187. {
  188. result = "FLOAT";
  189. }
  190. else if (type == typeof(Boolean))
  191. {
  192. result = "Bool";
  193. }
  194. return result;
  195. }
  196. /// <summary>
  197. /// 创建数据库
  198. /// </summary>
  199. /// <param name="tableName">数据库名</param>
  200. /// <param name="colNames">字段名</param>
  201. /// <param name="colTypes">字段名类型</param>
  202. /// <returns></returns>
  203. public SqliteDataReader CreateTable(string tableName, string[] colNames, string[] colTypes)
  204. {
  205. string queryString = "create table " + tableName + "(" + colNames[0] + " " + colTypes[0];
  206. for (int i = 1; i < colNames.Length; i++)
  207. {
  208. queryString += ", " + colNames[i] + " " + colTypes[i];
  209. }
  210. queryString += " )";
  211. Debug.Log("添加成功");
  212. return ExecuteQuery(queryString);
  213. }
  214. /// <summary>
  215. /// 向指定数据表中插入数据
  216. /// </summary>
  217. /// <param name="tableName"></param>
  218. /// <param name="values"></param>
  219. /// <returns></returns>
  220. public SqliteDataReader InsertValues(string tableName, string[] values)
  221. {
  222. string sql = "INSERT INTO " + tableName + " values (";
  223. foreach (var item in values)
  224. {
  225. sql += "'" + item + "',";
  226. }
  227. sql = sql.TrimEnd(',') + ")";
  228. Debug.Log("插入成功");
  229. return ExecuteQuery(sql);
  230. }
  231. /// <summary>
  232. /// 插入数据
  233. /// </summary>
  234. /// <typeparam name="T"></typeparam>
  235. /// <param name="t"></param>
  236. /// <returns></returns>
  237. public SqliteDataReader Insert<T>(T t)
  238. {
  239. var type = typeof(T);
  240. var fields = type.GetFields();
  241. string sql = "INSERT INTO " + type.Name + " values (";
  242. foreach (var field in fields)
  243. {
  244. //通过反射得到对象的值
  245. sql += "'" + type.GetField(field.Name).GetValue(t) + "',";
  246. }
  247. sql = sql.TrimEnd(',') + ");";
  248. Debug.Log("插入成功");
  249. return ExecuteQuery(sql);
  250. }
  251. /// <summary>
  252. /// 更新数据
  253. /// </summary>
  254. /// <param name="tableName"></param>
  255. /// <param name="values">需要修改的数据</param>
  256. /// <param name="conditions">修改的条件</param>
  257. /// <returns></returns>
  258. public SqliteDataReader UpdataData(string tableName, string[] values, string[] conditions)
  259. {
  260. string sql = "update " + tableName + " set ";
  261. for (int i = 0; i < values.Length - 1; i += 2)
  262. {
  263. sql += values[i] + "='" + values[i + 1] + "',";
  264. }
  265. sql = sql.TrimEnd(',') + " where (";
  266. for (int i = 0; i < conditions.Length - 1; i += 2)
  267. {
  268. sql += conditions[i] + "='" + conditions[i + 1] + "' and ";
  269. }
  270. sql = sql.Substring(0, sql.Length - 4) + ");";
  271. Debug.Log("更新成功");
  272. return ExecuteQuery(sql);
  273. }
  274. /// <summary>
  275. /// 删除数据
  276. /// </summary>
  277. /// <param name="tableName"></param>
  278. /// <param name="conditions">查询条件</param>
  279. /// <returns></returns>
  280. public SqliteDataReader DeleteValues(string tableName, string[] conditions)
  281. {
  282. string sql = "delete from " + tableName + " where (";
  283. for (int i = 0; i < conditions.Length - 1; i += 2)
  284. {
  285. sql += conditions[i] + "='" + conditions[i + 1] + "' and ";
  286. }
  287. sql = sql.Substring(0, sql.Length - 4) + ");";
  288. return ExecuteQuery(sql);
  289. }
  290. //打开数据库
  291. public void OpenConnect()
  292. {
  293. try
  294. {
  295. //数据库存放在 Asset/StreamingAssets
  296. string path = Application.streamingAssetsPath + "/" + dbName + ".db";
  297. //新建数据库连接
  298. connection = new SqliteConnection(@"Data Source = " + path);
  299. //打开数据库
  300. connection.Open();
  301. Debug.Log("打开数据库");
  302. }
  303. catch (Exception ex)
  304. {
  305. Debug.Log(ex.ToString());
  306. }
  307. }
  308. //关闭数据库
  309. public void CloseDB()
  310. {
  311. if (command != null)
  312. {
  313. command.Cancel();
  314. }
  315. command = null;
  316. if (reader != null)
  317. {
  318. reader.Close();
  319. }
  320. reader = null;
  321. if (connection != null)
  322. {
  323. //connection.Close();
  324. }
  325. connection = null;
  326. Debug.Log("关闭数据库");
  327. }
  328. }

--------------------------解释问题--------------------------------

类中的对象是私有对象type.GetFields()得到的数据是空的,需要是public 对象。或者是使用属性也可以。如下:

  1. /// 创建表(使用泛型)
  2. /// </summary>
  3. /// <typeparam name="T"></typeparam>
  4. public void CreateTable<T>() {
  5. var type = typeof(T);
  6. string sql = string.Format("create Table {0}( ", type.Name);
  7. var fields = type.GetProperties();
  8. for (int i = 0; i < fields.Length; i++)
  9. {
  10. sql += string.Format(" {0} {1},", fields[i].Name, CS2DB(fields[i].PropertyType));
  11. }
  12. sql = sql.TrimEnd(',') + ")";
  13. ExecuteQuery(sql);
  14. }

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

闽ICP备14008679号