85 lines
3.1 KiB
C#
85 lines
3.1 KiB
C#
using Microsoft.Data.Sqlite;
|
|
|
|
namespace Controllers.DataBase {
|
|
|
|
public class DbDriver {
|
|
|
|
static bool Initilized = false;
|
|
|
|
public DbDriver() {
|
|
// Load in the datastore if not already loaded
|
|
if (!Initilized) {
|
|
// Open a connection with auto dispose when done
|
|
using (SqliteConnection sqlite = new SqliteConnection("Data Source=test.db")) {
|
|
// Open the connection
|
|
sqlite.Open();
|
|
// Create the key value store if not exist
|
|
using var command = sqlite.CreateCommand();
|
|
command.CommandText = """
|
|
CREATE TABLE IF NOT EXISTS KeyValuePair (
|
|
key TEXT NOT NULL,
|
|
value TEXT,
|
|
PRIMARY KEY(key)
|
|
);
|
|
""";
|
|
// Run the command
|
|
command.ExecuteReader();
|
|
}
|
|
}
|
|
}
|
|
|
|
// Return Values from keys
|
|
public string Get(string Key) {
|
|
// Open a connection with auto dispose when done
|
|
using (SqliteConnection sqlite = new SqliteConnection("Data Source=test.db")) {
|
|
// Open the connection
|
|
sqlite.Open();
|
|
// Create the key value store if not exist
|
|
using var command = sqlite.CreateCommand();
|
|
command.CommandText = """
|
|
SELECT value
|
|
FROM KeyValuePair
|
|
Where key = $key;
|
|
""";
|
|
// Add the parameter to prevent sql injection
|
|
command.Parameters.AddWithValue("$key", Key);
|
|
// Run the command
|
|
using var reader = command.ExecuteReader();
|
|
// Read off the result if exists
|
|
if (reader.Read()) {
|
|
// Return the results
|
|
return reader.GetString(0);
|
|
}
|
|
// Return something if nothing existed
|
|
return "";
|
|
}
|
|
}
|
|
|
|
// Set a key value pair in the store
|
|
public void Set(string Key, string Value) {
|
|
// Open a connection with auto dispose when done
|
|
using (SqliteConnection sqlite = new SqliteConnection("Data Source=test.db")) {
|
|
// Open the connection
|
|
sqlite.Open();
|
|
// Create the key value store if not exist
|
|
using var command = sqlite.CreateCommand();
|
|
command.CommandText = """
|
|
INSERT INTO KeyValuePair
|
|
(key,value)
|
|
VALUES
|
|
($key, $value)
|
|
ON CONFLICT(key)
|
|
DO UPDATE
|
|
SET value = excluded.value;
|
|
""";
|
|
// Add the parameters to prevent sql injection
|
|
command.Parameters.AddWithValue("$key", Key);
|
|
command.Parameters.AddWithValue("$value", Value);
|
|
// Process the command
|
|
command.ExecuteReader();
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
} |