using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mono.Data.Sqlite;
public class DataBaseControl : MonoSingleton<DataBaseControl> {
/// <summary>
/// 帮助我们与数据库建立连接
/// </summary>
SqliteConnection connection;
/// <summary>
/// 数据库执行命令对象
/// </summary>
SqliteCommand command;
/// <summary>
/// 查询结果
/// </summary>
SqliteDataReader reader;
public DataBaseControl()
{
#if UNITY_EDITOR
string datePath = "Data Source=" + Application.dataPath + "/" + "MySqliteTest.sqlite;Pooling=true";
#elif UNITY_IPHONE
string dataPath="Data Source="+Application.persistentDataPath+"/"+"MySqliteTest.sqlite";
#endif
try
{
if (connection == null)
{
connection = new SqliteConnection (datePath);
}
}
catch (SqliteException ex)
{
Debug.Log(ex);
}
try
{
command = connection.CreateCommand();
}
catch (SqliteException ex)
{
Debug.Log(ex);
}
}
/// <summary>
/// 打开数据库
/// </summary>
private void OpenDataBase()
{
try
{
connection.Open();
}
catch (SqliteException ex)
{
Debug.Log(ex);
}
}
/// <summary>
/// 关闭数据库
/// </summary>
private void CloseDataBase()
{
try
{
connection.Close();
}
catch (SqliteException ex)
{
Debug.Log(ex);
}
}
//ExecuteNonQuery() 没有返回值
//
/// <summary>
/// 执行 不返回数据
/// </summary>
/// <param name="sql"></param>
public void ExecSql(string sql)
{
OpenDataBase();
try
{
command.CommandText = sql;
command.ExecuteNonQuery();
}
catch (SqliteException ex)
{
throw;
}
CloseDataBase();
}
/// <summary>
/// 返回第一条数据
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public object SelectFileSql(string sql)
{
OpenDataBase();
object obj = null;
try
{
command.CommandText = sql;
obj = command.ExecuteScalar();
}
catch (SqliteException ex)
{
Debug.Log(ex);
}
CloseDataBase();
return obj;
}
/// <summary>
/// 返回第一条 并返回一个0 和1 的数字,代表返回的数据是否为空
/// </summary>
/// <param name="sql"></param>
/// <param name="hasResult"></param>
/// <returns></returns>
public object SelectFileSql(string sql ,out int hasResult)
{
OpenDataBase();
object obj = null;
hasResult = 0;
try
{
command.CommandText = sql;
obj = command.ExecuteScalar();
hasResult = obj.GetType() == typeof(System.DBNull) ? 0 : 1;
}
catch (SqliteException ex)
{
Debug.Log(ex);
}
CloseDataBase();
return obj;
}
/// <summary>
/// 执行返回所有数据
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public List<ArrayList > SelectResultSql(string sql)
{
OpenDataBase();
List<ArrayList> list = new List<ArrayList>();
try
{
command.CommandText = sql;
reader = command.ExecuteReader();
while (reader.Read())
{
ArrayList alist = new ArrayList();
for (int i = 0; i < reader.FieldCount; i++)
{
alist.Add(reader.GetValue(i));
}
list.Add(alist);
}
}
catch (SqliteException ex)
{
Debug.Log(ex);
}
reader.Close();
CloseDataBase();
return list;
}
}
查询数据库工具
猜你喜欢
转载自blog.csdn.net/yuan_bowen/article/details/80571095
今日推荐
周排行