using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mono.Data.Sqlite;
/*
* Author:W
* sqlite轻量型数据库使用
* 【注意:记得把Mono.Data.Sqlite.dll文件放在项目工程的Plugins文件夹下】
*/
public class SqlLiteManager : MonoBehaviour
{
public static SqlLiteManager Instance;
private SqliteConnection sqliteConnection;
private SqliteCommand sqliteCommand;
void Awake()
{
Instance = this;
}
/// <summary>
/// 数据库打开
/// </summary>
/// <param name="path"></param>
public void Open(string path)
{
sqliteConnection = new SqliteConnection("Data Source="+path);
if (sqliteConnection != null)
sqliteConnection.Open();
}
/// <summary>
/// 执行命令
/// 创建一张表SQL语句
/// sqlStr = "create table if not exists User(uid integer primary key autoincrement, name text,score integer)";
/// 添加一条数据
/// sqlStr = "insert into User(name,score) values('W',66)";
/// 删除一条数据
/// sqlStr ="delete from User where uid=1 ";
/// 修改一条数据
/// sqlStr = "update User set name='L' where uid = 1";
/// </summary>
/// <param name="sqlStr"></param>
public void ExcuteNonQuery(string sqlStr)
{
sqliteCommand = new SqliteCommand(sqlStr,sqliteConnection);
if (sqliteCommand == null) return;
sqliteCommand.ExecuteNonQuery();
sqliteCommand.Dispose();
}
/// <summary>
/// 执行单个结果查询
/// sqlStr ="select count(*) from User";
/// sqlStr = "select * from User where uid = 1";
/// </summary>
/// <param name="sqlStr"></param>
/// <returns></returns>
public object ExcuteScaler(string sqlStr)
{
sqliteCommand = new SqliteCommand(sqlStr, sqliteConnection);
if (sqliteCommand == null) return null;
object value =sqliteCommand.ExecuteScalar();
sqliteCommand.Dispose();
return value;
}
/// <summary>
/// 执行多个结果查询
/// sqlStr = "select * from User";
/// </summary>
/// <param name="sqlStr"></param>
/// <returns></returns>
public SqliteDataReader ExcuteQuery(string sqlStr)
{
sqliteCommand = new SqliteCommand(sqlStr,sqliteConnection);
if (sqliteCommand == null) return null;
SqliteDataReader reader = sqliteCommand.ExecuteReader();
sqliteCommand.Dispose();
reader.Close();
return reader;
}
/// <summary>
/// 数据库关闭
/// </summary>
private void Close()
{
if (sqliteConnection != null)
sqliteConnection.Close();
}
}
Unity关于轻量级数据库Sqlite的封装使用
最新推荐文章于 2024-11-08 14:34:57 发布