80 lines
2.5 KiB
C#
80 lines
2.5 KiB
C#
using Microsoft.Data.Sqlite;
|
|
|
|
namespace DataBase {
|
|
|
|
public class DbDriver : IDisposable {
|
|
|
|
static SqliteConnection? singletonConnector = null;
|
|
|
|
public DbDriver() {
|
|
// Load in the datastore if not already loaded
|
|
if (singletonConnector == null) {
|
|
singletonConnector = new SqliteConnection("Data Source=test.db");
|
|
singletonConnector.Open();
|
|
|
|
// Create the key value store if not exist
|
|
using var command = singletonConnector.CreateCommand();
|
|
command.CommandText = """
|
|
CREATE TABLE IF NOT EXISTS KeyValuePair (
|
|
key TEXT NOT NULL,
|
|
value TEXT,
|
|
PRIMARY KEY(key)
|
|
);
|
|
""";
|
|
command.ExecuteReader();
|
|
}
|
|
}
|
|
|
|
// Return Values from keys
|
|
public string Get(string Key) {
|
|
if (singletonConnector != null) {
|
|
using var command = singletonConnector.CreateCommand();
|
|
command.CommandText = """
|
|
SELECT value
|
|
FROM KeyValuePair
|
|
Where key = $key;
|
|
""";
|
|
command.Parameters.AddWithValue("$key", Key);
|
|
command.ExecuteReader();
|
|
using var reader = command.ExecuteReader();
|
|
if (reader.Read()) {
|
|
return reader.GetString(0);
|
|
}
|
|
}
|
|
return "";
|
|
}
|
|
|
|
// Set a key value pair in the store
|
|
public void Set(string Key, string Value) {
|
|
if (singletonConnector != null) {
|
|
using var command = singletonConnector.CreateCommand();
|
|
command.CommandText = """
|
|
INSERT INTO KeyValuePair
|
|
(key,value)
|
|
VALUES
|
|
($key, $value)
|
|
ON CONFLICT(key)
|
|
DO UPDATE
|
|
SET value = excluded.value;
|
|
""";
|
|
command.Parameters.AddWithValue("$key", Key);
|
|
command.Parameters.AddWithValue("$value", Value);
|
|
command.ExecuteReader();
|
|
}
|
|
}
|
|
|
|
// Deconstructor
|
|
~DbDriver() {
|
|
Dispose();
|
|
}
|
|
|
|
// Deconstructor
|
|
public void Dispose() {
|
|
if (singletonConnector != null) {
|
|
singletonConnector.Close();
|
|
singletonConnector = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
} |