IndieGame/client/Assets/Ether/Scripts/Module/DataBase/Sqlite/SqliteManager.cs

326 lines
11 KiB
C#
Raw Normal View History

2024-10-11 10:12:15 +08:00
/********************************************************************
: SqliteManager.cs
:
: 1982614048@qq.com
: 2024/03/29 17:28:19
:
: 2024/04/03 16:04:51
: sqlite本地数据库管理类()
使
SqliteManager.Inst.CreateTable("role", new List<DataBaseColumnTypeData>()
{
new DataBaseColumnTypeData(){ columnName = "角色id", columnType = DataBaseColumnType.Int, isAutoInchement = true, isPrimaryKey = true},
new DataBaseColumnTypeData(){ columnName = "角色名称", columnType = DataBaseColumnType.VarChar, parameter = new List<int>() { 10 }, isNotNull = true},
new DataBaseColumnTypeData(){ columnName = "等级", columnType = DataBaseColumnType.Int, isNotNull = true},
});
DataBaseManager.Inst.DelectTable("role");
DataBaseManager.Inst.Update("role", new List<(string, string)>()
{
("角色名称", "11"),
}, new List<DataBaseFitter>() {
//new DataBaseFitter()
//{
// columnName = "角色名称",
// fitterType = DataBaseFitterType.Equal,
// fitterValue = "32",
//},
new DataBaseFitter()
{
columnName = "等级",
fitterType = DataBaseFitterType.GreaterlEqual,
fitterValue = "20",
},
});
SqliteManager.Inst.Select("role", new List<DataBaseFitter>()
{
new DataBaseFitter()
{
columnName = "角色名称",
fitterType = DataBaseFitterType.Equal,
fitterValue = "11"
}
});
*********************************************************************/
using Mono.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace Ether
{
public class SqliteManager : Singleton<SqliteManager>
{
private readonly static string dataBaseDirectory = $"{Application.persistentDataPath}/DB"; //数据库文件夹沙盒路径
private const string dataBaseName = "ether.db"; //数据库名称
private readonly static string databasePath = $"{dataBaseDirectory}/{dataBaseName}"; // 数据库文件沙盒路径
private readonly static string streamingAssetsDatabasePath = $"{Application.streamingAssetsPath}/DB/{dataBaseName}"; // streamingAssets数据库文件名称
static SqliteConnection connection;//创建一个数据库链接事件对象
private SqliteCommand command;
private SqliteDataReader reader;
/// <summary>
/// 数据库链接
/// </summary>
public void Connect()
{
// 定义数据库连接字符串
string connectionString = $"URI = file:{databasePath};Version=3;"; //Android"URI = file:" + Application.dataPath + "test.db";
// 创建数据库连接
//传入创建或者访问SQLITE数据库的路径
connection = new SqliteConnection(connectionString);
//判断沙盒是否有数据库文件如果没有则将streamingAssets中的数据库文件拷贝过去
if (File.Exists(databasePath))
{
connection?.Open();//打开数据库
command = connection.CreateCommand();
Debug.Log("Sqlite数据库链接完毕已打开");
}
else
{
if (File.Exists(streamingAssetsDatabasePath))
{
if (!Directory.Exists(dataBaseDirectory))
{
Directory.CreateDirectory(dataBaseDirectory);
}
try
{
File.Copy(streamingAssetsDatabasePath, databasePath);
Debug.Log("Sqlite数据库文件复制成功");
connection?.Open();//打开数据库
command = connection.CreateCommand();
Debug.Log("Sqlite数据库链接完毕已打开");
}
catch (Exception ex)
{
Debug.Log("Sqlite数据库文件复制失败" + ex.Message);
}
}
else
{
Debug.LogError("streamingAssets中Sqlite数据库文件不存在");
}
}
}
/// <summary>
/// 断开数据库链接
/// </summary>
public void DisConnect()
{
command?.Dispose();
command = null;
connection?.Close();
Debug.Log("Sqlite数据库链接已关闭");
}
/// <summary>
/// 创建表
/// </summary>
/// <param name="tableName"></param>
/// <param name="tableColumnDataList"></param>
public void CreateTable(string tableName, List<DataBaseColumnTypeData> tableColumnDataList)
{
string columnSqlStr = "";
for (int i = 0; i < tableColumnDataList.Count; i++)
{
if (i == 0)
{
columnSqlStr += DataBaseColumnTypeData.FormatColumnType(tableColumnDataList[i]);
}
else
{
columnSqlStr += "," + DataBaseColumnTypeData.FormatColumnType(tableColumnDataList[i]);
}
}
string commandStr = $"CREATE TABLE IF NOT EXISTS {tableName}({columnSqlStr}); ";
Debug.Log("Sqlite创建表Sql:" + commandStr);
command.CommandText = commandStr;
command.ExecuteNonQuery();
}
/// <summary>
/// 删除表
/// </summary>
/// <param name="tableName"></param>
public void DropTable(string tableName)
{
string commandStr = $"DROP TABLE IF EXISTS {tableName}; ";
Debug.Log("Sqlite删除表Sql:" + commandStr);
command.CommandText = commandStr;
command.ExecuteNonQuery();
}
#region
/// <summary>
/// 增加数据
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="insertDataList">插入数据</param>
public void Insert(string tableName, List<(string, string)> insertDataList)
{
if (insertDataList.Count <= 0)
{
Debug.LogError("Sqlite插入表数据为空请检查数据");
return;
}
string columnNameList = "";
string columnValeList = "";
for (int i = 0; i < insertDataList.Count; i++)
{
if (i == 0)
{
columnNameList += insertDataList[i].Item1;
columnValeList += insertDataList[i].Item2;
}
else
{
columnNameList += "," + insertDataList[i].Item1;
columnValeList += "," + insertDataList[i].Item2;
}
}
string commandStr = $"INSERT INTO {tableName} ({columnNameList}) VALUES ({columnValeList});";
Debug.Log("Sqlite插入表Sql:" + commandStr);
command.CommandText = commandStr;
command.ExecuteNonQuery();
}
#endregion
#region
/// <summary>
/// 删除数据
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="fitterList">条件</param>
public void Delete(string tableName, List<DataBaseFitter> fitterList)
{
if (fitterList.Count <= 0)
{
Debug.LogError("Sqlite删除表数据为空请检查数据");
return;
}
string condition = "";
for (int i = 0; i < fitterList.Count; i++)
{
if (i == 0)
{
condition += $"{fitterList[i].columnName} {DataBaseFitter.FormatFitter(fitterList[i].fitterType)} {fitterList[i].fitterValue}";
}
else
{
condition += $" AND {fitterList[i].columnName} {DataBaseFitter.FormatFitter(fitterList[i].fitterType)} {fitterList[i].fitterValue}";
}
}
string commandStr = $"DELETE FROM {tableName} WHERE {condition};";
Debug.Log("Sqlite删除表记录Sql:" + commandStr);
command.CommandText = commandStr;
command.ExecuteNonQuery();
}
#endregion
#region
public void Update(string tableName, List<(string, string)> setValues, List<DataBaseFitter> fitterList)
{
if (setValues.Count <= 0)
{
Debug.LogError("Sqlite修改表数据为空请检查数据");
return;
}
string setStr = "";
for (int i = 0; i < setValues.Count; i++)
{
if (i == 0)
{
setStr += $"{setValues[i].Item1} = '{setValues[i].Item2}'";
}
else
{
setStr += $",{setValues[i].Item1} = '{setValues[i].Item2}'";
}
}
string condition = "";
for (int i = 0; i < fitterList.Count; i++)
{
if (i == 0)
{
condition += $"{fitterList[i].columnName} {DataBaseFitter.FormatFitter(fitterList[i].fitterType)} {fitterList[i].fitterValue}";
}
else
{
condition += $" AND {fitterList[i].columnName} {DataBaseFitter.FormatFitter(fitterList[i].fitterType)} {fitterList[i].fitterValue}";
}
}
string commandStr = $"UPDATE {tableName} SET {setStr} WHERE {condition};";
Debug.Log("Sqlite修改表记录Sql:" + commandStr);
command.CommandText = commandStr;
command.ExecuteNonQuery();
}
#endregion
#region
public SqliteDataReader Select(string tableName, List<DataBaseFitter> fitterList = null, int limitNum = 0)
{
string condition = "";
if (fitterList != null)
{
for (int i = 0; i < fitterList.Count; i++)
{
if (i == 0)
{
condition += $"WHERE {fitterList[i].columnName} {DataBaseFitter.FormatFitter(fitterList[i].fitterType)} {fitterList[i].fitterValue}";
}
else
{
condition += $" AND {fitterList[i].columnName} {DataBaseFitter.FormatFitter(fitterList[i].fitterType)} {fitterList[i].fitterValue}";
}
}
}
string limit = limitNum > 0 ? $"LIMIT {limitNum}" : "";
string commandStr = $"SELECT * FROM {tableName} {condition} {limit};";
Debug.Log("Sqlite查询表记录Sql:" + commandStr);
command.CommandText = commandStr;
SqliteDataReader read = command.ExecuteReader();
return read;
}
#endregion
}
}