[Unity]SQLite-C#调用
SQLite数据库-Unity操作
项目开发的时候,经常会遇到的一种需求,数据存储
离线缓存的数据类型很多,大致分成两类
- 字符串文本数据
- 多媒体数据
字符串数据的类型只有字符串,但是结构有很多:
- xml
- json
- md5
- base64
- 普通字符串
多媒体数据的类型:
- 图片(jpg,png,gif...)
- 音频(mp3,aif...)
- 视频(mp4,mpv)
通常用数据库来存储字符串文本类型的数据,但是需要注意的是数据库同时也能存储多媒体类型的数据
关系数据库
在一个给定的应用领域中,所有实体及实体之间联系的集合构成一个关系数据库。
目前主流的关系数据库有oracle、db2、sqlserver、sybase、mysql等。
在Unity中打开数据库函数
private string GetDBPath(string name)
{
return Application.persistentDataPath + "/" + name + ".sqlite";
}
/// <summary>
/// 就是用来存储程序与数据库链接的对象
/// </summary>
private SqliteConnection connection = null;
private void OpenDataBase()
{
//获取一个数据库文件的路径
string path = GetDBPath ("xiaohao");
string c = "Data Source=" + path;
//需要通过数据库文件磁盘路径进行初始化
connection = new SqliteConnection (c);
//打开数据库
connection.Open();
}
CRUD
创建表格SQL
create table lo_human(human_id integer,human_name text,human_age integer);
C#函数调用创建表格SQL
private void CreateObject()
{
//在一个数据库链接对象上创建一个命令对象
SqliteCommand command = new SqliteCommand(connection);
//给命令对象添加SQL语句
command.CommandText = "create table if not exists lo_human(human_id integer,human_name text,human_age integer);";
//执行命令
command.ExecuteNonQuery();
}
添加数据
insert into lo_human(human_id,human_name,human_age) values(1,'xiaohao',36);
C#函数调用添加数据SQL
private void InsertObject()
{
//在一个数据库链接对象上创建一个命令对象
SqliteCommand command = new SqliteCommand (connection);
//给命令对象添加SQL语句
command.CommandText = "insert into lo_human(human_id,human_name,human_age) values(1,'xiaohao',36);";
//执行命令
command.ExecuteNonQuery ();
}
更新数据
update lo_human set human_name='cuiyayun' where human_id=2;
C#函数调用更新数据SQL
private void UpdateObject()
{
//在一个数据库链接对象上创建一个命令对象
SqliteCommand command = new SqliteCommand (connection);
//给命令对象添加SQL语句
command.CommandText = "update lo_human set human_name='cuiyayun' where human_id=3;";
//执行命令
command.ExecuteNonQuery ();
}
删除数据
delete from lo_human where humanid=1;
C#函数调用删除数据SQL
private void DeleteObject()
{
//在一个数据库链接对象上创建一个命令对象
SqliteCommand command = new SqliteCommand (connection);
//给命令对象添加SQL语句
command.CommandText = "delete from lo_human where human_id=1;";
//执行命令
command.ExecuteNonQuery ();
}
查询数据
select * from lo_human where human_id>15 order by human_id desc;
C#函数调用查询数据SQL
private void SelectObject()
{
//在一个数据库链接对象上创建一个命令对象
SqliteCommand command = new SqliteCommand (connection);
//给命令对象添加SQL语句
command.CommandText = "select * from lo_human where human_id>15 order by human_id desc;";
//数据读取器
SqliteDataReader reader = command.ExecuteReader();
//判读是否可以读取下一行数据,如果可以的话就获取数据
while (reader.Read())
{
//在循环体里,已经确定是哪行数据.
Debug.Log(reader ["human_name"]);
}
}
高级用法
通过使用C#语言的反射机制实现工具类SQLiteTools
[AttributeUsage(AttributeTargets.Property)]
public class SQLFieldAttribute:Attribute
{
public string Name{ set; get;}
public string Type{ set; get;}
public bool IsNotNull{ set; get;}
public bool AutoIncrement{set;get;}
public bool IsPrimaryKey{set;get;}
public string Default{ set; get;}
public bool IsUnique{set;get;}
}
[AttributeUsage(AttributeTargets.Class)]
public class SQLTableAttribute:Attribute
{
public string Name{set;get;}
}
/// <summary>
/// 测试功能用到的类
/// </summary>
//创建TestClass附件的特性对象SQLTable,并且将该特性对象的属性Name赋值为"test_class"
[SQLTable(Name="test_class")]
public class TestClass
{
//创建test_id属性附件的特性对象SQLField,并且将该特性对象的属性Name、Type、AutoIncrement、IsNotNull、IsPrimaryKey进行赋值
[SQLField(Name="test_id",Type="integer",AutoIncrement=true,IsNotNull=true,IsPrimaryKey=true)]
public int test_id{set;get;}
[SQLField(Name="test_name",Type="text")]
public string test_name{set;get;}
[SQLField(Name="test_age",Type="integer")]
public int test_age{ set; get;}
public TestClass(){}
}
LOSQLiteTools.cs实现具体的功能
获取表格名称函数
/// <summary>
/// 获取表格的名称
/// </summary>
/// <returns>The table name.</returns>
private static string GetTableName(Type item)
{
//获取到特性类型
Type att_type = typeof(SQLTableAttribute);
//获取参数type对应的特性对象
Attribute a = Attribute.GetCustomAttribute(item,att_type);
if (a == null) {
return null;
}
//因为在Attribute.Get函数里的最后一个参数已经指定了
//特性的类型是SQLTableAttribute,所以可以显式转换
SQLTableAttribute sa = (SQLTableAttribute)a;
//将特性对象的Name属性返回
return sa.Name;
}
获取属性姓名函数
/// <summary>
/// 获取属性在Field中的名字
/// </summary>
private static string GetFieldName(PropertyInfo item)
{
Type att_type = typeof(SQLFieldAttribute);
Attribute a = Attribute.GetCustomAttribute (item, att_type);
if (a == null) {
return null;
}
SQLFieldAttribute sfa = (SQLFieldAttribute)a;
return sfa.Name;
}
获取属性类型函数
/// <summary>
/// 获取属性在Field中的类型
/// </summary>
private static string GetFieldType(PropertyInfo item)
{
Type att_type = typeof(SQLFieldAttribute);
Attribute a = Attribute.GetCustomAttribute (item, att_type);
if (a == null) {
return null;
}
SQLFieldAttribute sfa = (SQLFieldAttribute)a;
return sfa.Type;
}
获取属性区域字符串函数
/// <summary>
/// 获取创建表格时的Field字符串
/// </summary>
private static string GetFieldString(PropertyInfo item)
{
Type att_type = typeof(SQLFieldAttribute);
Attribute a = Attribute.GetCustomAttribute (item, att_type);
if (a == null) {
return null;
}
SQLFieldAttribute sfa = (SQLFieldAttribute)a;
string sql = "";
sql += sfa.Name + " ";
sql += sfa.Type + " ";
if (sfa.IsPrimaryKey) {
sql += "primary key" + " ";
}
if (sfa.AutoIncrement) {
sql += "autoincrement" + " ";
}
if (sfa.IsNotNull) {
sql += "not null" + " ";
}
if (sfa.IsUnique) {
sql += "unique" + " ";
}
if (sfa.Default != null) {
sql += "default " + sfa.Default;
}
return sql;
}
创建表格函数
/// <summary>
/// 通过实体类型创建数据库表格
/// </summary>
public static void CreateTable(Type type)
{
//获取一个类型的所有属性
PropertyInfo[] p_list = type.GetProperties();
//获取Table的名字
string table_name = GetTableName(type);
//获取Table的列名字符串
string field_list = "(";
foreach (PropertyInfo item in p_list)
{
//对应的属性区域
field_list += GetFieldString(item) + ",";
}
//删除最后一个,
field_list = field_list.Substring (0, field_list.Length - 1);
field_list += ")";
//开始构造sql命令
string sql = "create table if not exists ";
sql += table_name + field_list + ";";
Debug.Log (sql);
SqliteCommand command = new SqliteCommand (connection);
command.CommandText = sql;
command.ExecuteNonQuery ();
}
}
[Unity]SQLite-C#调用的更多相关文章
- Unity sqlite学习笔记一
1.SQLITE的常识 SQLite是一个开源免费的数据库,一般用于嵌入系统或者小规模的应用软件开发中,你可以像使用Access一样使用它. sqlite的主要优点:零配置(Zero Configur ...
- unity android相互调用
简介 有一些手机功能,Unity没有提供相应的接口,例如震动,例如不锁屏,例如GPS,例如... 有太多的特殊功能Unity都没有提供接口,这时候,我们就需要通过使用Android原生的ADT编辑器去 ...
- Unity&Sqlite数据库
Sqlite是一个跨平台关系型小型数据库,非常便利,适合于嵌入式设备:对于Sqlite数据库来说,这个数据库是以文件的形成存在的(比如data.db):数据库是由表组成的,在一个数据库里面可以存储多个 ...
- C#生成DLL,在Unity中导入/调用DLL
网上搜了一些DLL的创建.编写.使用的学习资料,感觉比较的凌乱.或是复杂抽象,或是关键地方一笔带过,不是很适合萌新.于是决定还是图文记录一下该过程,尽量精简而又明确. 学习资料: https://do ...
- Unity之定时调用
1.Invoke(string methodName,float time) 在一定时间调用methodName函数 using UnityEngine; using System.Collectio ...
- Unity SLua 如何调用Unity中C#方法
1.原理 就是通常在Lua框架中所说的,开放一个C#的web接口,或者叫做在Slua框架中注册函数. 2.作用 在Lua中调用C#中的方法,这个是在做热更新中很常用的一种方法,无论是slua,还是lu ...
- 【Unity】动态调用其他脚本的函数
本文转载自:http://blog.csdn.net/smilingeyes/article/details/17767269 第一种,被调用脚本函数为static类型,调用时直接用 脚本名.函数名( ...
- UNITY引擎变量调用产生不必要内存分配
https://unity3d.com/de/learn/tutorials/topics/performance-optimization/optimizing-garbage-collection ...
- unity, Awake的调用时机
Awake是在setActive(true)时才会被调用,不过如果再setActive(false)然后重新setActive(true)的话,Awake就不会再被调用了,也就是说Awake能保证仅被 ...
- Unity MonoBehaviour.Invoke 调用
使用 Invoke() 方法需要注意 3点: 1 :它应该在 脚本的生命周期里的(Start.Update.OnGUI.FixedUpdate.LateUpdate)中被调用: 2:Invoke(); ...
随机推荐
- Setup a private http/nginx based GIT server
原文:http://aaba.me/blog/2014/03/setup-a-private-http-nginx-based-git-server.html https://doomzhou.git ...
- 12c meet sysdba meet ORA-01017: invalid username/password; logon denied
checklist: 1.12c: threaded_execution=true Prevents OS Login As Sysdba 2. The following database para ...
- ngnix配置文件
使用nginx最大的好处就是负载均衡. #设定负载均衡的服务器列表 upstream service{ server 10.4.29.174:7477; } server { ...
- 事务(JDBC、Hibernate、Spring)
如果不用spring管理事务,我们自己写代码来操作事务.那么这个代码怎么写要看底层怎么访问数据库了. 当采用原生JDBC访问数据库时,操作事务需要使用java.sql.Connection的API.开 ...
- pat L2-006. 树的遍历
L2-006. 树的遍历 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历 ...
- 转:jmeter性能测试---登录百度进行搜索
在做web程序性能测试时,loadrunner和jmeter是两款常用的工具,两者比较起来,jmeter非常轻巧,且开源免费,上手快.这里简单介绍下jmeter的使用,以登录百度进行搜索为例. jme ...
- android性能优化优秀文章
郭霖最近整理的文章: 合理管理内存 分析编码过程中如何避免过多内存占用,以及如何实现高性能的内存使用. 尽可能使用intentService; 当界面不可见时释放内存; 当内存紧张时释放内存; 避免b ...
- Windows下python安装MySQLdb
安装MySQLdb需要在电脑上安装MySQL connector C,只需要这个connector就好,不需要把mysql装全. 另外,需要安装VC for python提供编译. 到官网上下载脚本进 ...
- qemu -hda /dev/sdc -m 1024 -vga std
同事拿了个烂u盘让我给他做个启动盘,用cp *.iso /dev/sdc怎么也启动不了. 改用dd if=copied/20140923/debian-7.6.0-amd64-DVD-1.iso of ...
- TIdTCPClient 详解
转发地址:http://blog.csdn.net/cowcga/article/details/6198382 关于TIdTCPClient的几种方法 收藏 其实Indy比较简单,但是可以提供的方法 ...