在unity中利用内嵌数据库sqlite

莱莱  金牌会员 | 2024-9-17 17:52:08 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 876|帖子 876|积分 2628

前言



  • 这个任务是因为我在给别人写外包,必要数据库。
  • 假如利用MySQL,实在是太笨重了,必要额外安装MySQL这个软件
  • 所以我决定用sqlite这个嵌入式数据库。
网络上两种环境



  • 第一种是利用这两个dll来进行毗连并创建,在本身电脑上就可以很轻易的找到,我这里利用的是everythingTool工具,所以比较方便找到了。


  • 视频教程B站视频
  • 第二种是github上某人写的一个毗连库
    视频教程
  • 我这里利用的是第二种
  • 数据库可视化工具用的sqliteStudio
  • GitHub毗连
如何利用



  • 导入插件
    插件
  • 写脚本,毗连数据库。
  • 再者,创建数据表
  • 留意事项
  • 1.他这个插件会根据你的类自动创建对应的表的表头,假如你必要主键,就必要继承IPrimaryKey
  • 而且因为我没找到怎么让她自动天生主键,所以我是本身用Guid来填充的
  • 2.在测试阶段退出player后肯定要关闭和数据库的connection,否则你没有办法删除天生的表。
三个脚本



  • 脚本是我根据插件里面自带的例子更改而成的
  • model模型类,用来对表的数据做映射
  • Table类-提供基本的对表的增编削查的操作,比如按照ID搜索,按照名字搜索等等。
  • ModelManager,用table的方法来提供对上层的支持
  1. using SQLite4Unity3d;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. public enum Role
  6. {
  7.     None = 0,
  8.     InWork = 1,
  9.     LoseWork = 2,
  10.     ExitWork = 3,
  11.     Other = 4,
  12. }
  13. public enum Major
  14. {
  15.     None = 0,
  16.     Machine = 1,
  17.     NotMachine = 2
  18. }
  19. public interface IPrimaryKey
  20. {
  21.     public string ID { get; set; }
  22. }
  23. public class User : IPrimaryKey
  24. {
  25.     [PrimaryKey]
  26.     public string ID { get; set; }
  27.     public string UserName { get; set; }
  28.     public string Password { get; set; }
  29.     public Role Role { get; set; } = Role.None;
  30.     public string Name { get; set; }
  31.     public int StudyNumber { get; set; }
  32.     public Major MajorCode { get; set; }
  33. }
复制代码


  • 通用的表类
  1. using SQLite4Unity3d;
  2. using UnityEngine;
  3. #if !UNITY_EDITOR
  4. using System.Collections;
  5. using System.IO;
  6. #endif
  7. using System.Collections.Generic;
  8. public class UserTable : TableService<User>
  9. {
  10.     public User FindByUserName(string name)
  11.     {
  12.         return _connection.Table<User>().Where(x => x.UserName == name).FirstOrDefault();
  13.     }
  14. }
  15. public class TableService<T> where T : IPrimaryKey, new()
  16. {
  17.     protected static SQLiteConnection _connection;
  18.     public static void DisConnect()
  19.     {
  20.         _connection.Dispose();
  21.     }
  22.     const string DatabaseName = "Crane.db";
  23.     static TableService()
  24.     {
  25. #if UNITY_EDITOR
  26.         var dbPath = string.Format(@"Assets/StreamingAssets/{0}", DatabaseName);
  27. #else
  28.         // check if file exists in Application.persistentDataPath
  29.         var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName);
  30.         if (!File.Exists(filepath))
  31.         {
  32.             Debug.Log("Database not in Persistent path");
  33.             // if it doesn't ->
  34.             // open StreamingAssets directory and load the db ->
  35. #if UNITY_ANDROID
  36.             var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName);  // this is the path to your StreamingAssets in android
  37.             while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
  38.             // then save to Application.persistentDataPath
  39.             File.WriteAllBytes(filepath, loadDb.bytes);
  40. #elif UNITY_IOS
  41.                  var loadDb = Application.dataPath + "/Raw/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
  42.                 // then save to Application.persistentDataPath
  43.                 File.Copy(loadDb, filepath);
  44. #elif UNITY_WP8
  45.                 var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
  46.                 // then save to Application.persistentDataPath
  47.                 File.Copy(loadDb, filepath);
  48. #elif UNITY_WINRT
  49.                 var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
  50.                 // then save to Application.persistentDataPath
  51.                 File.Copy(loadDb, filepath);
  52.                
  53. #elif UNITY_STANDALONE_OSX
  54.                 var loadDb = Application.dataPath + "/Resources/Data/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
  55.                 // then save to Application.persistentDataPath
  56.                 File.Copy(loadDb, filepath);
  57. #else
  58.         var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
  59.         // then save to Application.persistentDataPath
  60.         File.Copy(loadDb, filepath);
  61. #endif
  62.             Debug.Log("Database written");
  63.         }
  64.         var dbPath = filepath;
  65. #endif
  66.         _connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
  67.         Debug.Log("Final PATH: " + dbPath);
  68.         var count = _connection.GetTableInfo(typeof(T).Name).Count;
  69.         //创建对应的Table
  70.         if (count == 0)
  71.         {
  72.             _connection.CreateTable<T>();
  73.         }
  74.     }
  75.     public int InsertData(T obj)
  76.     {
  77.         return _connection.Insert(obj);
  78.     }
  79.     public int Delete(T obj)
  80.     {
  81.         return _connection.Delete(obj);
  82.     }
  83.     public int Update(T obj)
  84.     {
  85.         return _connection.Update(obj);
  86.     }
  87.     public T FindByID(string ID)
  88.     {
  89.         return _connection.Table<T>().Where(x => x.ID == ID).FirstOrDefault();
  90.     }
  91.     //public void CreateDB<T>()
  92.     //{
  93.     //    _connection.CreateTable<T>();
  94.     //}
  95.     //public IEnumerable<Person> GetPersons()
  96.     //{
  97.     //    //_connection.
  98.     //    return _connection.Table<Person>();
  99.     //}
  100.     //public IEnumerable<Person> GetPersonsNamedRoberto()
  101.     //{
  102.     //    return _connection.Table<Person>().Where(x => x.Name == "Roberto");
  103.     //}
  104.     //public Person GetJohnny()
  105.     //{
  106.     //    return _connection.Table<Person>().Where(x => x.Name == "Johnny").FirstOrDefault();
  107.     //}
  108.     //public Person CreatePerson()
  109.     //{
  110.     //    var p = new Person
  111.     //    {
  112.     //        Name = "Johnny",
  113.     //        Surname = "Mnemonic",
  114.     //        Age = 21
  115.     //    };
  116.     //    _connection.Insert(p);
  117.     //    return p;
  118.     //}
  119. }
复制代码


  • ModelMaanger
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using Unity.VisualScripting;
  7. using UnityEngine;
  8. public class ModelManager
  9. {
  10.     public static UserTable UserTable;
  11.     public static ModelManager Inst { get; private set; } = new ModelManager();
  12.     static ModelManager()
  13.     {
  14.         UserTable = new UserTable();
  15.     }
  16.     private ModelManager()
  17.     {
  18.     }
  19.     public void OnQuit()
  20.     {
  21.         UserTable.DisConnect();
  22.     }
  23.     public void RegisterUser(User user)
  24.     {
  25.         user.ID = Guid.NewGuid().ToString();
  26.         user.Password = EnCryption(user.Password + salt);
  27.         UserTable.InsertData(user);
  28.     }
  29.     public bool IsExistName(string name, out User user)
  30.     {
  31.         var currUser = UserTable.FindByUserName(name);
  32.         user = currUser;
  33.         return currUser != null;
  34.     }
  35.     public bool IsExistName(string name)
  36.     {
  37.         var currUser = UserTable.FindByUserName(name);
  38.         return currUser != null;
  39.     }
  40.     public void UpdatePassword(User user, string password)
  41.     {
  42.         user.Password = EnCryption(password + salt);
  43.         UserTable.Update(user);
  44.     }
  45.     public bool IsMatchName(string name, string password, out bool passwordRight)
  46.     {
  47.         var currUser = UserTable.FindByUserName(name);
  48.         if (currUser == null)
  49.         {
  50.             passwordRight = false;
  51.             return false;
  52.         }
  53.         else
  54.         {
  55.             passwordRight = EnCryption(password + salt) == currUser.Password;
  56.             return true;
  57.         }
  58.     }
  59.     string salt = "sdsax";
  60.     public string EnCryption(string content)
  61.     {
  62.         using (MD5 md5Hash = MD5.Create())
  63.         {
  64.             byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(content));
  65.             StringBuilder builder = new StringBuilder();
  66.             for (int i = 0; i < data.Length; i++)
  67.             {
  68.                 builder.Append(data[i].ToString("x2")); // 将每个字节转换为十六进制并添加到结果中
  69.             }
  70.             return builder.ToString();
  71.         }
  72.     }
  73. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

莱莱

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表