Unity C# SQLite4Unity的介绍
为什么要记录这一篇呢?使用过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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | using SQLite4Unity3d; using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; public class Sqlite3BaseTable { [PrimaryKey, AutoIncrement] public int Id { get ; set ; } public Sqlite3BaseTable() { } } public class DataService { private SQLiteConnection _connection; public DataService( string DatabaseName) { #if UNITY_EDITOR var dbPath = string .Format( @"Assets/StreamingAssets/DB/{0}" , DatabaseName); if (!Directory.Exists( @"Assets/StreamingAssets/DB/" )) { Directory.CreateDirectory( @"Assets/StreamingAssets/DB/" ); UnityEditor.AssetDatabase.Refresh(); } #else // check if file exists in Application.persistentDataPath var filepath = string .Format( "{0}/{1}" , Application.persistentDataPath, DatabaseName); if (!File.Exists(filepath)) { Debug.Log( "Database not in Persistent path" ); // if it doesn't -> // open StreamingAssets directory and load the db -> #if UNITY_ANDROID var loadDb = new WWW( "jar:file://" + Application.dataPath + "!/assets/" + DatabaseName); // this is the path to your StreamingAssets in android while (!loadDb.isDone) { } // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check // then save to Application.persistentDataPath File.WriteAllBytes(filepath, loadDb.bytes); #elif UNITY_IOS var loadDb = Application.dataPath + "/Raw/" + DatabaseName; // this is the path to your StreamingAssets in iOS // then save to Application.persistentDataPath File.Copy(loadDb, filepath); #elif UNITY_WP8 var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS // then save to Application.persistentDataPath File.Copy(loadDb, filepath); #elif UNITY_WINRT var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS // then save to Application.persistentDataPath File.Copy(loadDb, filepath); #elif UNITY_STANDALONE_OSX var loadDb = Application.dataPath + "/Resources/Data/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS // then save to Application.persistentDataPath File.Copy(loadDb, filepath); #else var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS // then save to Application.persistentDataPath File.Copy(loadDb, filepath); #endif Debug.Log( "Database written" ); } var dbPath = filepath; #endif _connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create); Debug.Log( "Final PATH: " + dbPath); } public void CreateTable<T>() { _connection.DropTable<T>(); _connection.CreateTable<T>(); } /// <summary> /// 插入多条数据到表中 /// </summary> /// <param name="objects"></param> /// <returns>插入到表中数据额条数</returns> public int InsertDataToTable(IEnumerable objects) { return _connection.InsertAll(objects); } /// <summary> /// 插入一条数据到表中 /// </summary> /// <param name="obj"></param> /// <returns>插入到表中数据额条数</returns> public int InsertDataToTable<T>(T obj) where T:Sqlite3BaseTable { return _connection.Insert(obj); } public T GetRowById<T>( int id) where T:Sqlite3BaseTable, new () { //var ret = from x in _connection.Table<T>() // where x.Id == id // select x; //return ret.FirstOrDefault(); return _connection.Table<T>().Where(x => x.Id == id).FirstOrDefault(); } /// <summary> /// 删除表 /// </summary> /// <typeparam name="T"></typeparam> public void DropTable<T>() { _connection.DropTable<T>(); } public IEnumerable<T> GetAllRows<T>() where T:Sqlite3BaseTable, new () { return _connection.Table<T>(); } } |
DataService 可以帮助我们创建和数据库操纵的链接,以及其他操作
例如创建数据库的操作
1 2 3 4 5 6 7 | public void CreateTable<T>() { //删除数据库 _connection.DropTable<T>(); //创建数据库 _connection.CreateTable<T>(); } |
插入多条数据的操作
1 2 3 4 5 6 7 8 9 | /// <summary> /// 插入多条数据到表中 /// </summary> /// <param name="objects"></param> /// <returns>插入到表中数据额条数</returns> public int InsertDataToTable(IEnumerable objects) { return _connection.InsertAll(objects); } |
插入一条数据
1 2 3 4 5 6 7 8 9 | /// <summary> /// 插入一条数据到表中 /// </summary> /// <param name="obj"></param> /// <returns>插入到表中数据额条数</returns> public int InsertDataToTable<T>(T obj) where T:Sqlite3BaseTable { return _connection.Insert(obj); } |
通过Id 的带一条数据
下面展示了两种操作数据的方式 ,在实际操作中任选其一
1 2 3 4 5 6 7 8 9 10 | public T GetRowById<T>( int id) where T:Sqlite3BaseTable, new () { //使用linq 操作数据库 var ret = from x in _connection.Table<T>() where x.Id == id select x; return ret.FirstOrDefault(); //使用lambda 表达式 return _connection.Table<T>().Where(x => x.Id == id).FirstOrDefault(); } |
删除表的操作
1 2 3 4 5 6 7 8 | /// <summary> /// 删除表 /// </summary> /// <typeparam name="T"></typeparam> public void DropTable<T>() { _connection.DropTable<T>(); } |
得到所有的条目数据
1 2 3 4 | public IEnumerable<T> GetAllRows<T>() where T:Sqlite3BaseTable, new () { return _connection.Table<T>(); } |
以上针对与数据库的操作都支持Linq ,在此篇文章中不在赘述。可参考 通过Id 的带一条数据的操作
从其构造函数中可以看出,他支持多个平台,ANDROID,iOS,WP8,Window,并且它的数据库文件在Assets/StreamingAssets/DB 目录下,如果在创建的时候目录不存在,则会帮猿媛们创建对应的目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | public DataService( string DatabaseName) { #if UNITY_EDITOR var dbPath = string .Format( @"Assets/StreamingAssets/DB/{0}" , DatabaseName); if (!Directory.Exists( @"Assets/StreamingAssets/DB/" )) { Directory.CreateDirectory( @"Assets/StreamingAssets/DB/" ); UnityEditor.AssetDatabase.Refresh(); } #else // check if file exists in Application.persistentDataPath var filepath = string .Format( "{0}/{1}" , Application.persistentDataPath, DatabaseName); if (!File.Exists(filepath)) { Debug.Log( "Database not in Persistent path" ); // if it doesn't -> // open StreamingAssets directory and load the db -> #if UNITY_ANDROID var loadDb = new WWW( "jar:file://" + Application.dataPath + "!/assets/" + DatabaseName); // this is the path to your StreamingAssets in android while (!loadDb.isDone) { } // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check // then save to Application.persistentDataPath File.WriteAllBytes(filepath, loadDb.bytes); #elif UNITY_IOS var loadDb = Application.dataPath + "/Raw/" + DatabaseName; // this is the path to your StreamingAssets in iOS // then save to Application.persistentDataPath File.Copy(loadDb, filepath); #elif UNITY_WP8 var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS // then save to Application.persistentDataPath File.Copy(loadDb, filepath); #elif UNITY_WINRT var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS // then save to Application.persistentDataPath File.Copy(loadDb, filepath); #elif UNITY_STANDALONE_OSX var loadDb = Application.dataPath + "/Resources/Data/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS // then save to Application.persistentDataPath File.Copy(loadDb, filepath); #else var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS // then save to Application.persistentDataPath File.Copy(loadDb, filepath); #endif Debug.Log( "Database written" ); } var dbPath = filepath; #endif _connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create); Debug.Log( "Final PATH: " + dbPath); } |
SQlite4Unity的插件是不是很强大!由于篇幅较长,SQLite的介绍先到这里,下一篇我们介绍SQlite4Unity的使用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!