当前位置:   article > 正文

unity连接sqlite数据库操作_unity using unity.visualscripting.dependencies.sql

unity using unity.visualscripting.dependencies.sqlite;

原文链接:http://www.unitymanual.com/bbs/thread-198-1-1.html

最近几天在讨论游戏本地数据存储方式,考虑到跨平台性。最开始打算用xml,但是考虑到xml文件多而杂,而且后期游戏更新。也不是很方便,于是提出了采用sqlite,可是没想到的是原本信心满满的我却遭到了闭门羹,呵呵....

原来,不是用 以前做c#  winform应用那套dll, unity 3d有自己对应的sqlite.dll分别需要三个文件
1.Mono.Data.Sqlite.dll 
在unity安装文件“Unity\Editor\Data\MonoBleedingEdge\lib\mono”可以找到,注意mono文件夹下面 有对应版本号,可以根据自己的项目来决定选择。

2.System.Data.dll   同上位置一样可以找到 ,不过建议使用2.0版本

3.sqlite3.dll   就在\Unity\Editor下可以找到

除此之外,还需要把这3个文件放在你的项目的这个路径下面:\Assets\Plugins\,没有Plugins文件夹就必须创建这个文件夹,然后将这三个dll文件放在该文件夹下面。当然,如果你想能够在PC上面发布成可执行文件,还需要改动一些地方。在 unity3d 中的Play Setting ->Other Setting 中将Api Compatibility的等级改为.NET 2.0;那么这些操作做完了以后,如果你的代码写得没有 问题 ,那么你就可以成功了。

好啦 ,前面准工作完成 下面就直接看测试代码吧
首先是一个 Sqlite的数据库操作类,该类是我改编的 网上也有很多,不过好像是js编写,于是自己动手改编成了c#希望能对大家有用,呵呵...

好了,上类 SqliteDbHelper

  1. using UnityEngine;
  2. using System.Collections;
  3. using Mono.Data.Sqlite;<span style="font-family: 'microsoft yahei';">//导入sqlite数据集,也就是Plugins文件夹下的那个dll文件</span>
  4. using System;<span style="font-family: 'microsoft yahei';">//数据集 是formwork2.0 用vs开发要自己引用框架中的System.Data</span>
  5. using System.Data;
  1. public class SqliteDbHelper
  2. {
  3. /// <summary>
  4. /// 声明一个连接对象
  5. /// </summary>
  6. private SqliteConnection dbConnection;
  7. /// <summary>
  8. /// 声明一个操作数据库命令
  9. /// </summary>
  10. private SqliteCommand dbCommand;
  11. /// <summary>
  12. /// 声明一个读取结果集的一个或多个结果流
  13. /// </summary>
  14. private SqliteDataReader reader;
  15. /// <summary>
  16. /// 数据库的连接字符串,用于建立与特定数据源的连接
  17. /// </summary>
  18. /// <param name="connectionString">数据库的连接字符串,用于建立与特定数据源的连接</param>
  19. public SqliteDbHelper (string connectionString)
  20. {
  21. <span style="white-space:pre"> </span>OpenDB(connectionString);
  22. Debug.Log(connectionString);
  23. }
  24. public void OpenDB (string connectionString)
  25. {
  26. try
  27. {
  28. dbConnection = new SqliteConnection (connectionString);
  29. dbConnection.Open();
  30. Debug.Log ("Connected to db");
  31. }
  32. catch(Exception e)
  33. {
  34. string temp1 = e.ToString();
  35. Debug.Log(temp1);
  36. }
  37. }
  38. /// <summary>
  39. /// 关闭连接
  40. /// </summary>
  41. public void CloseSqlConnection ()
  42. {
  43. if (dbCommand != null)
  44. {
  45. <span style="white-space:pre"> </span>dbCommand.Dispose();
  46. }
  47. dbCommand = null;
  48. if (reader != null)
  49. {
  50. reader.Dispose ();
  51. }
  52. reader = null;
  53. if (dbConnection != null)
  54. {
  55. dbConnection.Close ();
  56. }
  57. dbConnection = null;
  58. Debug.Log ("Disconnected from db.");
  59. }
  60. /// <summary>
  61. /// 执行查询sqlite语句操作
  62. /// </summary>
  63. /// <param name="sqlQuery"></param>
  64. /// <returns></returns>
  65. public SqliteDataReader ExecuteQuery (string sqlQuery)
  66. {
  67. dbCommand = dbConnection.CreateCommand ();
  68. dbCommand.CommandText = sqlQuery;
  69. reader = dbCommand.ExecuteReader ();
  70. return reader;
  71. }
  72. /// <summary>
  73. /// 查询该表所有数据
  74. /// </summary>
  75. /// <param name="tableName">表名</param>
  76. /// <returns></returns>
  77. public SqliteDataReader ReadFullTable (string tableName)
  78. {
  79. string query = "SELECT * FROM " + tableName;
  80. return ExecuteQuery (query);
  81. }
  82. /// <summary>
  83. /// 动态添加表字段到指定表
  84. /// </summary>
  85. /// <param name="tableName">表名</param>
  86. /// <param name="values">字段集合</param>
  87. /// <returns></returns>
  88. public SqliteDataReader InsertInto (string tableName, string[] values)
  89. {
  90. string query = "INSERT INTO " + tableName + " VALUES (" + values[0];
  91. for (int i = 1; i < values.Length; ++i)
  92. {
  93. query += ", " + values;
  94. }
  95. query += ")";
  96. return ExecuteQuery (query);
  97. }
  98. /// <summary>
  99. /// 动态更新表结构
  100. /// </summary>
  101. /// <param name="tableName">表名</param>
  102. /// <param name="cols">字段集</param>
  103. /// <param name="colsvalues">对于集合值</param>
  104. /// <param name="selectkey">要查询的字段</param>
  105. /// <param name="selectvalue">要查询的字段值</param>
  106. /// <returns></returns>
  107. public SqliteDataReader UpdateInto (string tableName, string []cols, string []colsvalues,string selectkey,string selectvalue)
  108. {
  109. string query = "UPDATE "+tableName+" SET "+cols[0]+" = "+colsvalues[0];
  110. for (int i = 1; i < colsvalues.Length; ++i) 
  1. <span style="white-space:pre"> </span> {
  2. query += ", " +cols+" ="+ colsvalues;
  3. }
  4. query += " WHERE "+selectkey+" = "+selectvalue+" ";
  5. return ExecuteQuery (query);
  6. }
  7. /// <summary>
  8. /// 动态删除指定表字段数据
  9. /// </summary>
  10. /// <param name="tableName">表名</param>
  11. /// <param name="cols">字段</param>
  12. /// <param name="colsvalues">字段值</param>
  13. /// <returns></returns>
  14. public SqliteDataReader Delete(string tableName,string []cols,string []colsvalues)
  15. {
  16. string query = "DELETE FROM "+tableName + " WHERE " +cols[0] +" = " + colsvalues[0];
  17. for (int i = 1; i < colsvalues.Length; ++i)
  18. {
  19. query += " or " +cols+" = "+ colsvalues;
  20. }
  21. Debug.Log(query);
  22. return ExecuteQuery (query);
  23. }
  24. /// <summary>
  25. /// 动态添加数据到指定表
  26. /// </summary>
  27. /// <param name="tableName">表名</param>
  28. /// <param name="cols">字段</param>
  29. /// <param name="values"></param>
  30. /// <returns></returns>
  31. public SqliteDataReader InsertIntoSpecific (string tableName, string[] cols, string[] values)
  32. {
  33. if (cols.Length != values.Length)
  34. {
  35. throw new SqliteException ("columns.Length != values.Length");
  36. }
  37. string query = "INSERT INTO " + tableName + "(" + cols[0];
  38. for (int i = 1; i < cols.Length; ++i)
  39. {
  40. query += ", " + cols;
  41. }
  42. query += ") VALUES (" + values[0];
  43. for (int i = 1; i < values.Length; ++i)
  44. {
  45. query += ", " + values;
  46. }
  47. query += ")";
  48. return ExecuteQuery (query);
  49. }
  50. /// <summary>
  51. /// 动态删除表
  52. /// </summary>
  53. /// <param name="tableName">表名</param>
  54. /// <returns></returns>
  55. public SqliteDataReader DeleteContents (string tableName)
  56. {
  57. string query = "DELETE FROM " + tableName;
  58. return ExecuteQuery (query);
  59. }
  60. /// <summary>
  61. /// 动态创建表
  62. /// </summary>
  63. /// <param name="name">表名</param>
  64. /// <param name="col">字段</param>
  65. /// <param name="colType">类型</param>
  66. /// <returns></returns>
  67. public SqliteDataReader CreateTable (string name, string[] col, string[] colType)
  68. {
  69. if (col.Length != colType.Length)
  70. {
  71. throw new SqliteException ("columns.Length != colType.Length");
  72. }
  73. string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];
  74. for (int i = 1; i < col.Length; ++i)
  75. {
  76. query += ", " + col + " " + colType;
  77. }
  78. query += ")";
  79. Debug.Log(query);
  80. return ExecuteQuery (query);
  81. }
  82. /// <summary>
  83. /// 根据查询条件 动态查询数据信息
  84. /// </summary>
  85. /// <param name="tableName"></param>
  86. /// <param name="items">查询数据集合</param>
  87. /// <param name="col">字段</param>
  88. /// <param name="operation">操作</param>
  89. /// <param name="values"></param>
  90. /// <returns></returns>
  91. public SqliteDataReader SelectWhere (string tableName, string[] items, string[] col, string[] operation, string[] values)
  92. {
  93. if (col.Length != operation.Length || operation.Length != values.Length)
  94. {
  95. throw new SqliteException ("col.Length != operation.Length != values.Length");
  96. }
  97. string query = "SELECT " + items[0];
  98. for (int i = 1; i < items.Length; ++i)
  99. {
  100. query += ", " + items;
  101. }
  102. query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
  103. for (int i = 1; i < col.Length; ++i)
  104. {
  105. query += " AND " + col + operation + "'" + values[0] + "' ";
  106. }
  107. return ExecuteQuery (query);
  108. }
  109. }
好了 sqlite数据操作类写好后:本来应该按照编码规范来写  因为我本身以前做c#的所有一般使用三层架构
Modle实例化对象类 ,DAl数据处理类,IDal数据接口类,Bll业务逻辑类
但是呢,目前只为测试 因此我就不一一详细介绍代码内容了,相信会c#的人都会三层架构,呵呵

ok,言归正传,下面将贴出unity3d 使用上面 sqliteDbHelper 操作类
SqliteDbTest:
  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4. using Mono.Data.Sqlite;
  5. using System.Data;
  1. public class SqliteDbTest : MonoBehaviour {
  2. <span style="white-space:pre"> </span>SqliteDbHelper db ;
  3. <span style="white-space:pre"> </span>int id=1;
  4. void Start ()
  5. {
  6. db = new SqliteDbHelper("Data Source=./sqlite.db");
  7. Debug.Log(db.ToString());
  8. /*
  9. SqliteDbAccess db = new SqliteDbAccess("data source=mydb1.db");
  10. db.CreateTable("momo",new string[]{"name","qq","email","blog"},
  11. new string[]{"text","text","text","text"});
  12. db.CloseSqlConnection();
  13. */
  14. }  
  1. <span style="white-space:pre"> </span>public string name = "";
  2. public string emls = "";
  3. void OnGUI()
  4. {
  5. if(GUILayout.Button("create table"))
  6. {
  7. db.CreateTable("mytable",new string[]{"id","name","email"},new string[]{"int","varchar(20)","varchar(50)"});
  8. Debug.Log("create table ok");
  9. }
  10. if(GUILayout.Button("insert data"))
  11. {
  12. db.InsertInto("mytable",
  13. new string[] { "" + (++id), "'随风去旅行"+id+"'","'zhangj_live"+id+"@163.com'"});//),"'aaa"+id+"'","'aaa"+id+"@sohu.com'"});
  14. Debug.Log("insert table ok");
  15. }
  16. if(GUILayout.Button("search database"))
  17. {
  18. IDataReader sqReader = db.SelectWhere("mytable", new string[]
  19. {"name","email"},new string[]{"id"},new string[]{"="},new string[]{"2"});
  20. while (sqReader.Read())
  21. {
  22. //Debug.Log(
  23. name= "name="+sqReader.GetString(sqReader.GetOrdinal("name"));// +
  24. emls = "email=" + sqReader.GetString(sqReader.GetOrdinal("email"));
  25. //);
  26. }
  27. }
  28. if (name != "")
  29. {
  30. GUI.Label(new Rect(100, 100, 100, 100), name);
  31. GUI.Label(new Rect(100, 200, 100, 100), emls);
  32. // GUILayout.Label(emls);
  33. }
  34. if(GUILayout.Button("close database"))
  35. {
  36. db.CloseSqlConnection();
  37. Debug.Log("close table ok");
  38. }
  39. }
  40. }
上面的代码很简单 ,相信稍微懂点unity3d的,都能看懂 因此就小偷懒一般 没写注释了,呵呵

由此可以看出 分别实现了
1.动态创建数据库及表结构
2.动态创加入数据
3,.查询指定字段
4.关闭数据连接

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

闽ICP备14008679号