ROIEditor/DatabaseManager.cs

114 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.Data.Sqlite;
using System.ComponentModel;
namespace ROIEditor
{
public class DatabaseManager<T>
{
private readonly string connectionString;
private readonly string tableName;
private List<T> data = new List<T>();
public void Add(T item)
{
data.Add(item);
}
public void Clear()
{
data.Clear();
}
public List<T> GetList()
{
return data;
}
public int Count => data.Count;
public DatabaseManager(string dbPath, string tableName)
{
connectionString = $"Data Source={dbPath}";
this.tableName = tableName;
InitializeDatabase();
}
private void InitializeDatabase()
{
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = $@"
CREATE TABLE IF NOT EXISTS {tableName} (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Clave TEXT,
SerializeData TEXT
)";
command.ExecuteNonQuery();
}
}
public void SaveData(string clave)
{
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var deleteCommand = connection.CreateCommand();
deleteCommand.CommandText = @"DELETE FROM Roi WHERE Clave = $Clave";
deleteCommand.Parameters.AddWithValue("$Clave", clave);
deleteCommand.ExecuteNonQuery();
foreach (var elemento in data)
{
string serializedData = JsonSerializer.Serialize(elemento);
var command = connection.CreateCommand();
command.CommandText = $"INSERT INTO {tableName} (Clave, SerializeData) VALUES ($Clave, $SerializedData)";
command.Parameters.AddWithValue("$Clave", clave);
command.Parameters.AddWithValue("$SerializedData", serializedData);
command.ExecuteNonQuery();
}
}
}
public List<T> LoadData(string clave)
{
var dataList = new List<T>();
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = $"SELECT SerializeData FROM {tableName} WHERE Clave = $Clave";
command.Parameters.AddWithValue("$Clave", clave);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string serializedData = reader.GetString(0);
List<T> data = JsonSerializer.Deserialize<List<T>>(serializedData);
dataList.AddRange(data);
}
}
}
return dataList;
}
}
}