SQLite数据库-Unity操作

项目开发的时候,经常会遇到的一种需求,数据存储

离线缓存的数据类型很多,大致分成两类

  • 字符串文本数据
  • 多媒体数据

字符串数据的类型只有字符串,但是结构有很多:

  • xml
  • json
  • md5
  • base64
  • 普通字符串

多媒体数据的类型:

  • 图片(jpg,png,gif...)
  • 音频(mp3,aif...)
  • 视频(mp4,mpv)

通常用数据库来存储字符串文本类型的数据,但是需要注意的是数据库同时也能存储多媒体类型的数据


关系数据库

在一个给定的应用领域中,所有实体及实体之间联系的集合构成一个关系数据库。

目前主流的关系数据库有oracle、db2、sqlserver、sybase、mysql等。

在Unity中打开数据库函数

  1. private string GetDBPath(string name)
  2. {
  3. return Application.persistentDataPath + "/" + name + ".sqlite";
  4. }
  5. /// <summary>
  6. /// 就是用来存储程序与数据库链接的对象
  7. /// </summary>
  8. private SqliteConnection connection = null;
  9. private void OpenDataBase()
  10. {
  11. //获取一个数据库文件的路径
  12. string path = GetDBPath ("xiaohao");
  13. string c = "Data Source=" + path;
  14. //需要通过数据库文件磁盘路径进行初始化
  15. connection = new SqliteConnection (c);
  16. //打开数据库
  17. connection.Open();
  18. }

CRUD


创建表格SQL

  1. create table lo_human(human_id integer,human_name text,human_age integer);

C#函数调用创建表格SQL

  1. private void CreateObject()
  2. {
  3. //在一个数据库链接对象上创建一个命令对象
  4. SqliteCommand command = new SqliteCommand(connection);
  5. //给命令对象添加SQL语句
  6. command.CommandText = "create table if not exists lo_human(human_id integer,human_name text,human_age integer);";
  7. //执行命令
  8. command.ExecuteNonQuery();
  9. }

添加数据

  1. insert into lo_human(human_id,human_name,human_age) values(1,'xiaohao',36);

C#函数调用添加数据SQL

  1. private void InsertObject()
  2. {
  3. //在一个数据库链接对象上创建一个命令对象
  4. SqliteCommand command = new SqliteCommand (connection);
  5. //给命令对象添加SQL语句
  6. command.CommandText = "insert into lo_human(human_id,human_name,human_age) values(1,'xiaohao',36);";
  7. //执行命令
  8. command.ExecuteNonQuery ();
  9. }

更新数据

  1. update lo_human set human_name='cuiyayun' where human_id=2;

C#函数调用更新数据SQL

  1. private void UpdateObject()
  2. {
  3. //在一个数据库链接对象上创建一个命令对象
  4. SqliteCommand command = new SqliteCommand (connection);
  5. //给命令对象添加SQL语句
  6. command.CommandText = "update lo_human set human_name='cuiyayun' where human_id=3;";
  7. //执行命令
  8. command.ExecuteNonQuery ();
  9. }

删除数据

  1. delete from lo_human where humanid=1;

C#函数调用删除数据SQL

  1. private void DeleteObject()
  2. {
  3. //在一个数据库链接对象上创建一个命令对象
  4. SqliteCommand command = new SqliteCommand (connection);
  5. //给命令对象添加SQL语句
  6. command.CommandText = "delete from lo_human where human_id=1;";
  7. //执行命令
  8. command.ExecuteNonQuery ();
  9. }

查询数据

  1. select * from lo_human where human_id>15 order by human_id desc;

C#函数调用查询数据SQL

  1. private void SelectObject()
  2. {
  3. //在一个数据库链接对象上创建一个命令对象
  4. SqliteCommand command = new SqliteCommand (connection);
  5. //给命令对象添加SQL语句
  6. command.CommandText = "select * from lo_human where human_id>15 order by human_id desc;";
  7. //数据读取器
  8. SqliteDataReader reader = command.ExecuteReader();
  9. //判读是否可以读取下一行数据,如果可以的话就获取数据
  10. while (reader.Read())
  11. {
  12. //在循环体里,已经确定是哪行数据.
  13. Debug.Log(reader ["human_name"]);
  14. }
  15. }

高级用法

通过使用C#语言的反射机制实现工具类SQLiteTools

  1. [AttributeUsage(AttributeTargets.Property)]
  2. public class SQLFieldAttribute:Attribute
  3. {
  4. public string Name{ set; get;}
  5. public string Type{ set; get;}
  6. public bool IsNotNull{ set; get;}
  7. public bool AutoIncrement{set;get;}
  8. public bool IsPrimaryKey{set;get;}
  9. public string Default{ set; get;}
  10. public bool IsUnique{set;get;}
  11. }
  12. [AttributeUsage(AttributeTargets.Class)]
  13. public class SQLTableAttribute:Attribute
  14. {
  15. public string Name{set;get;}
  16. }
  17. /// <summary>
  18. /// 测试功能用到的类
  19. /// </summary>
  20. //创建TestClass附件的特性对象SQLTable,并且将该特性对象的属性Name赋值为"test_class"
  21. [SQLTable(Name="test_class")]
  22. public class TestClass
  23. {
  24. //创建test_id属性附件的特性对象SQLField,并且将该特性对象的属性Name、Type、AutoIncrement、IsNotNull、IsPrimaryKey进行赋值
  25. [SQLField(Name="test_id",Type="integer",AutoIncrement=true,IsNotNull=true,IsPrimaryKey=true)]
  26. public int test_id{set;get;}
  27. [SQLField(Name="test_name",Type="text")]
  28. public string test_name{set;get;}
  29. [SQLField(Name="test_age",Type="integer")]
  30. public int test_age{ set; get;}
  31. public TestClass(){}
  32. }

LOSQLiteTools.cs实现具体的功能

获取表格名称函数

  1. /// <summary>
  2. /// 获取表格的名称
  3. /// </summary>
  4. /// <returns>The table name.</returns>
  5. private static string GetTableName(Type item)
  6. {
  7. //获取到特性类型
  8. Type att_type = typeof(SQLTableAttribute);
  9. //获取参数type对应的特性对象
  10. Attribute a = Attribute.GetCustomAttribute(item,att_type);
  11. if (a == null) {
  12. return null;
  13. }
  14. //因为在Attribute.Get函数里的最后一个参数已经指定了
  15. //特性的类型是SQLTableAttribute,所以可以显式转换
  16. SQLTableAttribute sa = (SQLTableAttribute)a;
  17. //将特性对象的Name属性返回
  18. return sa.Name;
  19. }

获取属性姓名函数

  1. /// <summary>
  2. /// 获取属性在Field中的名字
  3. /// </summary>
  4. private static string GetFieldName(PropertyInfo item)
  5. {
  6. Type att_type = typeof(SQLFieldAttribute);
  7. Attribute a = Attribute.GetCustomAttribute (item, att_type);
  8. if (a == null) {
  9. return null;
  10. }
  11. SQLFieldAttribute sfa = (SQLFieldAttribute)a;
  12. return sfa.Name;
  13. }

获取属性类型函数

  1. /// <summary>
  2. /// 获取属性在Field中的类型
  3. /// </summary>
  4. private static string GetFieldType(PropertyInfo item)
  5. {
  6. Type att_type = typeof(SQLFieldAttribute);
  7. Attribute a = Attribute.GetCustomAttribute (item, att_type);
  8. if (a == null) {
  9. return null;
  10. }
  11. SQLFieldAttribute sfa = (SQLFieldAttribute)a;
  12. return sfa.Type;
  13. }

获取属性区域字符串函数

  1. /// <summary>
  2. /// 获取创建表格时的Field字符串
  3. /// </summary>
  4. private static string GetFieldString(PropertyInfo item)
  5. {
  6. Type att_type = typeof(SQLFieldAttribute);
  7. Attribute a = Attribute.GetCustomAttribute (item, att_type);
  8. if (a == null) {
  9. return null;
  10. }
  11. SQLFieldAttribute sfa = (SQLFieldAttribute)a;
  12. string sql = "";
  13. sql += sfa.Name + " ";
  14. sql += sfa.Type + " ";
  15. if (sfa.IsPrimaryKey) {
  16. sql += "primary key" + " ";
  17. }
  18. if (sfa.AutoIncrement) {
  19. sql += "autoincrement" + " ";
  20. }
  21. if (sfa.IsNotNull) {
  22. sql += "not null" + " ";
  23. }
  24. if (sfa.IsUnique) {
  25. sql += "unique" + " ";
  26. }
  27. if (sfa.Default != null) {
  28. sql += "default " + sfa.Default;
  29. }
  30. return sql;
  31. }

创建表格函数

  1. /// <summary>
  2. /// 通过实体类型创建数据库表格
  3. /// </summary>
  4. public static void CreateTable(Type type)
  5. {
  6. //获取一个类型的所有属性
  7. PropertyInfo[] p_list = type.GetProperties();
  8. //获取Table的名字
  9. string table_name = GetTableName(type);
  10. //获取Table的列名字符串
  11. string field_list = "(";
  12. foreach (PropertyInfo item in p_list)
  13. {
  14. //对应的属性区域
  15. field_list += GetFieldString(item) + ",";
  16. }
  17. //删除最后一个,
  18. field_list = field_list.Substring (0, field_list.Length - 1);
  19. field_list += ")";
  20. //开始构造sql命令
  21. string sql = "create table if not exists ";
  22. sql += table_name + field_list + ";";
  23. Debug.Log (sql);
  24. SqliteCommand command = new SqliteCommand (connection);
  25. command.CommandText = sql;
  26. command.ExecuteNonQuery ();
  27. }
  28. }

[Unity]SQLite-C#调用的更多相关文章

  1. Unity sqlite学习笔记一

    1.SQLITE的常识 SQLite是一个开源免费的数据库,一般用于嵌入系统或者小规模的应用软件开发中,你可以像使用Access一样使用它. sqlite的主要优点:零配置(Zero Configur ...

  2. unity android相互调用

    简介 有一些手机功能,Unity没有提供相应的接口,例如震动,例如不锁屏,例如GPS,例如... 有太多的特殊功能Unity都没有提供接口,这时候,我们就需要通过使用Android原生的ADT编辑器去 ...

  3. Unity&Sqlite数据库

    Sqlite是一个跨平台关系型小型数据库,非常便利,适合于嵌入式设备:对于Sqlite数据库来说,这个数据库是以文件的形成存在的(比如data.db):数据库是由表组成的,在一个数据库里面可以存储多个 ...

  4. C#生成DLL,在Unity中导入/调用DLL

    网上搜了一些DLL的创建.编写.使用的学习资料,感觉比较的凌乱.或是复杂抽象,或是关键地方一笔带过,不是很适合萌新.于是决定还是图文记录一下该过程,尽量精简而又明确. 学习资料: https://do ...

  5. Unity之定时调用

    1.Invoke(string methodName,float time) 在一定时间调用methodName函数 using UnityEngine; using System.Collectio ...

  6. Unity SLua 如何调用Unity中C#方法

    1.原理 就是通常在Lua框架中所说的,开放一个C#的web接口,或者叫做在Slua框架中注册函数. 2.作用 在Lua中调用C#中的方法,这个是在做热更新中很常用的一种方法,无论是slua,还是lu ...

  7. 【Unity】动态调用其他脚本的函数

    本文转载自:http://blog.csdn.net/smilingeyes/article/details/17767269 第一种,被调用脚本函数为static类型,调用时直接用 脚本名.函数名( ...

  8. UNITY引擎变量调用产生不必要内存分配

    https://unity3d.com/de/learn/tutorials/topics/performance-optimization/optimizing-garbage-collection ...

  9. unity, Awake的调用时机

    Awake是在setActive(true)时才会被调用,不过如果再setActive(false)然后重新setActive(true)的话,Awake就不会再被调用了,也就是说Awake能保证仅被 ...

  10. Unity MonoBehaviour.Invoke 调用

    使用 Invoke() 方法需要注意 3点: 1 :它应该在 脚本的生命周期里的(Start.Update.OnGUI.FixedUpdate.LateUpdate)中被调用: 2:Invoke(); ...

随机推荐

  1. 8.3 sikuli 集成进eclipse 报错:eclipse中运行提示 Win32Util.dll: Can't load 32-bit .dll on a AMD 64 bit platform

    sikuli运行出现问题:Win32Util.dll: Can't load 32-bit .dll on a AMD 64 bit platform 在64位平台上无法加载32位的dll文件 解决办 ...

  2. AJax的异步请求

    AJax的处理过程 1、传统的Web请求过程: 一般的 Web 应用程序中,用户填写表单字段并单击 Submit 按钮.然后整个表单发送到服务器,服务器将它转发给处理表单的脚本(通常是 PHP 或 J ...

  3. php 高并发下数据同步的问题

    1.加锁缺点:降低性能优点:减少代码逻辑复杂度(题主现在这样超过1w条就删数据的逻辑,感觉看起来就点糟糕啊,如果整个系统一复杂,这样的来回写数据,你确定你的逻辑还维护得下去?建议题主梳理一下代码的逻辑 ...

  4. js框架——angular.js(3)

    1. 过滤filter 过滤就是将内容进行筛选或者转换或者两者都有,一般的表示方式就是在变量后面添加"|",然后加上过滤条件,如—— {{name|currency}} 这个cur ...

  5. java 线程的同步

    Example12_7.java public class Example12_7 { public static void main(String args[]) { Bank bank = new ...

  6. messages exchanged between the client's and server's computers will never be lost, damaged, or received out of order. [1]

    w几乎所有的HTTP通信都由TCP/IP承载. HTTP The Definitive Guide Just about all of the world's HTTP communication i ...

  7. Chapter 1 First Sight——11

    I didn't relate well to people my age. 我没有向人们叙述清楚我的年龄 Maybe the truth was that I didn't relate well ...

  8. PHP无限极分类的几种方法

    导读:项目开发,经常栏目要做到无限极分类,几种方法PHP无限极分类的几种方法 复制代码 代码如下:namespace Util;class Category{static public functio ...

  9. jQuery两种扩展插件的方式

    <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...

  10. Web跨浏览器进程通信(Web跨域)

    Web跨域已是老生常谈的话题,这次来尝试下跨域浏览器进程之间的通信 —— 这在过去基本依靠网络中转实现   在之前一篇文章里尝试了跨浏览器的数据共享,最后提到使用LocalConnection还可以实 ...