当前位置:   article > 正文

C#系 SQLite4Unity的介绍_sqlite4unity3d

sqlite4unity3d

为什么要记录这一篇呢?使用过Unity的猿媛们可能知道,Unity使用的.net框架一般比较老,比如说Unity5.6.3使用的是.net3.5Framework 导致有很多高效的库无法使用,比如将汉字转笔画或者转拼音的一些库就无法使用。这让我在项目开发中很抓狂。为了能在Unity项目中高效的使用SQLite数据库,经过各种对比,此插件更胜一筹。特此记录一下来分享给各位猿媛!(不要问我为什么要在Unity 项目中使用SQLite,因为软件是不联网的,又要有很多数据的支撑)

SQLite4Unity3d 下载地址如下:

https://github.com/robertohuertasm/SQLite4Unity3d

下载完成后将按照下图中的路径找到Plugins目录和SQLite 导入到项目的Assets目录下

SQLite文件是对底层的一些封装,在后续操作中我们只需要在SQLite基础上进行操作即可

另外一个操作就是将DataService.cs导入到工程,这个操作其实是不一定是必要的,根据自己喜好。

此文件中定义了一些基础操作,我们可以直接利用

具体代码如下:

  1. using SQLite4Unity3d;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using System.IO;
  6. public class Sqlite3BaseTable
  7. {
  8. [PrimaryKey, AutoIncrement]
  9. public int Id { get; set; }
  10. public Sqlite3BaseTable()
  11. {
  12. }
  13. }
  14. public class DataService
  15. {
  16. private SQLiteConnection _connection;
  17. public DataService(string DatabaseName)
  18. {
  19. #if UNITY_EDITOR
  20. var dbPath = string.Format(@"Assets/StreamingAssets/DB/{0}", DatabaseName);
  21. if (!Directory.Exists(@"Assets/StreamingAssets/DB/"))
  22. {
  23. Directory.CreateDirectory(@"Assets/StreamingAssets/DB/");
  24. UnityEditor.AssetDatabase.Refresh();
  25. }
  26. #else
  27. // check if file exists in Application.persistentDataPath
  28. var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName);
  29. if (!File.Exists(filepath))
  30. {
  31. Debug.Log("Database not in Persistent path");
  32. // if it doesn't ->
  33. // open StreamingAssets directory and load the db ->
  34. #if UNITY_ANDROID
  35. var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName); // this is the path to your StreamingAssets in android
  36. while (!loadDb.isDone) { } // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
  37. // then save to Application.persistentDataPath
  38. File.WriteAllBytes(filepath, loadDb.bytes);
  39. #elif UNITY_IOS
  40. var loadDb = Application.dataPath + "/Raw/" + DatabaseName; // this is the path to your StreamingAssets in iOS
  41. // then save to Application.persistentDataPath
  42. File.Copy(loadDb, filepath);
  43. #elif UNITY_WP8
  44. var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
  45. // then save to Application.persistentDataPath
  46. File.Copy(loadDb, filepath);
  47. #elif UNITY_WINRT
  48. var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
  49. // then save to Application.persistentDataPath
  50. File.Copy(loadDb, filepath);
  51. #elif UNITY_STANDALONE_OSX
  52. var loadDb = Application.dataPath + "/Resources/Data/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
  53. // then save to Application.persistentDataPath
  54. File.Copy(loadDb, filepath);
  55. #else
  56. var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
  57. // then save to Application.persistentDataPath
  58. File.Copy(loadDb, filepath);
  59. #endif
  60. Debug.Log("Database written");
  61. }
  62. var dbPath = filepath;
  63. #endif
  64. _connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
  65. Debug.Log("Final PATH: " + dbPath);
  66. }
  67. public void CreateTable<T>()
  68. {
  69. _connection.DropTable<T>();
  70. _connection.CreateTable<T>();
  71. }
  72. /// <summary>
  73. /// 插入多条数据到表中
  74. /// </summary>
  75. /// <param name="objects"></param>
  76. /// <returns>插入到表中数据额条数</returns>
  77. public int InsertDataToTable(IEnumerable objects)
  78. {
  79. return _connection.InsertAll(objects);
  80. }
  81. /// <summary>
  82. /// 插入一条数据到表中
  83. /// </summary>
  84. /// <param name="obj"></param>
  85. /// <returns>插入到表中数据额条数</returns>
  86. public int InsertDataToTable<T>(T obj) where T:Sqlite3BaseTable
  87. {
  88. return _connection.Insert(obj);
  89. }
  90. public T GetRowById<T>(int id) where T:Sqlite3BaseTable,new()
  91. {
  92. //var ret = from x in _connection.Table<T>()
  93. // where x.Id == id
  94. // select x;
  95. //return ret.FirstOrDefault();
  96. return _connection.Table<T>().Where(x => x.Id == id).FirstOrDefault();
  97. }
  98. /// <summary>
  99. /// 删除表
  100. /// </summary>
  101. /// <typeparam name="T"></typeparam>
  102. public void DropTable<T>()
  103. {
  104. _connection.DropTable<T>();
  105. }
  106. public IEnumerable<T> GetAllRows<T>() where T:Sqlite3BaseTable,new()
  107. {
  108. return _connection.Table<T>();
  109. }
  110. }

DataService 可以帮助我们创建和数据库操纵的链接,以及其他操作

例如创建数据库的操作

  1. public void CreateTable<T>()
  2. {
  3.     //删除数据库
  4. _connection.DropTable<T>();
  5.     //创建数据库
  6. _connection.CreateTable<T>();
  7. }

插入多条数据的操作

  1. /// <summary>
  2. /// 插入多条数据到表中
  3. /// </summary>
  4. /// <param name="objects"></param>
  5. /// <returns>插入到表中数据额条数</returns>
  6. public int InsertDataToTable(IEnumerable objects)
  7. {
  8. return _connection.InsertAll(objects);
  9. }

插入一条数据

  1. /// <summary>
  2. /// 插入一条数据到表中
  3. /// </summary>
  4. /// <param name="obj"></param>
  5. /// <returns>插入到表中数据额条数</returns>
  6. public int InsertDataToTable<T>(T obj) where T:Sqlite3BaseTable
  7. {
  8. return _connection.Insert(obj);
  9. }

通过Id 的带一条数据

下面展示了两种操作数据的方式 ,在实际操作中任选其一

  1. public T GetRowById<T>(int id) where T:Sqlite3BaseTable,new()
  2. {
  3.     //使用linq 操作数据库
  4. var ret = from x in _connection.Table<T>()
  5. where x.Id == id
  6. select x;
  7. return ret.FirstOrDefault();
  8.     //使用lambda 表达式
  9. return _connection.Table<T>().Where(x => x.Id == id).FirstOrDefault();
  10. }

删除表的操作

  1. /// <summary>
  2. /// 删除表
  3. /// </summary>
  4. /// <typeparam name="T"></typeparam>
  5. public void DropTable<T>()
  6. {
  7. _connection.DropTable<T>();
  8. }

得到所有的条目数据

  1. public IEnumerable<T> GetAllRows<T>() where T:Sqlite3BaseTable,new()
  2. {
  3. return _connection.Table<T>();
  4. }

以上针对与数据库的操作都支持Linq ,在此篇文章中不在赘述。可参考 通过Id 的带一条数据的操作

从其构造函数中可以看出,他支持多个平台,ANDROID,iOS,WP8,Window,并且它的数据库文件在Assets/StreamingAssets/DB 目录下,如果在创建的时候目录不存在,则会帮猿媛们创建对应的目录

  1. public DataService(string DatabaseName)
  2. {
  3. #if UNITY_EDITOR
  4. var dbPath = string.Format(@"Assets/StreamingAssets/DB/{0}", DatabaseName);
  5. if (!Directory.Exists(@"Assets/StreamingAssets/DB/"))
  6. {
  7. Directory.CreateDirectory(@"Assets/StreamingAssets/DB/");
  8. UnityEditor.AssetDatabase.Refresh();
  9. }
  10. #else
  11. // check if file exists in Application.persistentDataPath
  12. var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName);
  13. if (!File.Exists(filepath))
  14. {
  15. Debug.Log("Database not in Persistent path");
  16. // if it doesn't ->
  17. // open StreamingAssets directory and load the db ->
  18. #if UNITY_ANDROID
  19. var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName); // this is the path to your StreamingAssets in android
  20. while (!loadDb.isDone) { } // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
  21. // then save to Application.persistentDataPath
  22. File.WriteAllBytes(filepath, loadDb.bytes);
  23. #elif UNITY_IOS
  24. var loadDb = Application.dataPath + "/Raw/" + DatabaseName; // this is the path to your StreamingAssets in iOS
  25. // then save to Application.persistentDataPath
  26. File.Copy(loadDb, filepath);
  27. #elif UNITY_WP8
  28. var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
  29. // then save to Application.persistentDataPath
  30. File.Copy(loadDb, filepath);
  31. #elif UNITY_WINRT
  32. var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
  33. // then save to Application.persistentDataPath
  34. File.Copy(loadDb, filepath);
  35. #elif UNITY_STANDALONE_OSX
  36. var loadDb = Application.dataPath + "/Resources/Data/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
  37. // then save to Application.persistentDataPath
  38. File.Copy(loadDb, filepath);
  39. #else
  40. var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
  41. // then save to Application.persistentDataPath
  42. File.Copy(loadDb, filepath);
  43. #endif
  44. Debug.Log("Database written");
  45. }
  46. var dbPath = filepath;
  47. #endif
  48. _connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
  49. Debug.Log("Final PATH: " + dbPath);
  50. }

SQlite4Unity的插件是不是很强大!由于篇幅较长,SQLite的介绍先到这里,下一篇我们介绍SQlite4Unity的使用

历史文章目录
https://blog.csdn.net/yy763496668/article/details/113117040
【关注、点赞,收藏】
关注公众号,您将第一时间收到文章更新
QQ群号:1056320746
微信公众号:猿媛大本营

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

闽ICP备14008679号