使用SQlite数据库,无非就是打开数据库-增删改差-关闭数据库的操作,而打开数据库前的准备工作呢就是,得出数据库的路径以及创建指令执行对象。话不多说,直接上干货。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Mono.Data.Sqlite;
public class DataBaseTool
{
public static DataBaseTool Instance=new DataBaseTool();
//数据库的连接对象
SqliteConnection con;
//指令执行对象
SqliteCommand command;
//查询结果集对象
SqliteDataReader reader;
private DataBaseTool()
{
//路径中,要注意StreamingAssets文件夹名称不要写错,同学们可以自行学习一些unity中的特殊文件夹。
string datapath = "Data source=" + Application.streamingAssetsPath + "/HeroEquip.sqlite";
try
{
if (con == null)
{
con = new SqliteConnection(datapath);
}
}
catch (System.Exception ex)
{
Debug.Log("数据库链接失败:" + ex);
}
try
{
command = con.CreateCommand();
}
catch (System.Exception ex)
{
Debug.Log("创建指令对象失败:" + ex);
}
Instance = this;
}
//打开数据库的操作
private void OpenDataBase()
{
try
{
con.Open();
}
catch (System.Exception ex)
{
Debug.Log("打开数据库失败" + ex);
}
}
//关闭数据库的操作
private void CloseDataBase()
{
try
{
con.Close();
}
catch (System.Exception ex)
{
Debug.Log("关闭数据库失败:" + ex);
}
}
//执行插入,删除,修改,更新的操作
public int ExecuteNonQuerySql(string sql)
{
//先打开数据库
OpenDataBase();
int value=-10;
try
{
command.CommandText = sql;
value =command.ExecuteNonQuery();
}
catch (System.Exception ex)
{
Debug.Log("执行语句出错:" + ex);
}
//关闭数据库
CloseDataBase();
return value;
}
//在获得数据库中一条数据时可以使用,必须游戏对象的每个等级的速度,攻击等等,由于得到的是object类型的数据,需要进行相应的转换。
public object ExcSelectOneItem(string sql)
{
OpenDataBase();
object obj = new object();
try
{
command.CommandText = sql;
obj = command.ExecuteScalar();
}
catch (System.Exception ex)
{
Debug.Log("数据库执行查询一条语句错误:"+ex);
}
CloseDataBase();
return obj;
}
//返回多个数据
public List<ArrayList> ExecuteMoreSql(string sql)
{
OpenDataBase();
List < ArrayList > list= new List<ArrayList>();
try
{
command.CommandText = sql;
reader = command.ExecuteReader();
while (reader.Read())
{
ArrayList arry = new ArrayList();
for (int i = 0; i < reader.FieldCount; i++)
{
arry.Add(reader.GetValue(i));
}
list.Add(arry);
}
reader.Close();
}
catch (System.Exception ex)
{
Debug.Log("查询数据错误:" + ex);
}
CloseDataBase();
return list;
}
}
以上就是封装数据库的方法,喜欢的同学可以参考一下。