-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDbServer.cs
88 lines (78 loc) · 2.94 KB
/
DbServer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using Npgsql;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace H24.Modules
{
internal class DbServer
{
private static string ConnectionString = Debugger.IsAttached ?
File.ReadAllText(@"C:\Users\Gustave\Desktop\Projects\PuzzleSolveR\PSR\connectionString.txt") :
File.ReadAllText("connectionString.txt");
public static void PerformQuery(Action<NpgsqlConnection> queryAction, Action<Exception> errorMessageHandler)
{
using (NpgsqlConnection sqlConnection = new NpgsqlConnection(DbServer.ConnectionString))
{
sqlConnection.Open();
try
{
queryAction(sqlConnection);
}
catch (Exception ex)
{
errorMessageHandler(ex);
}
finally
{
sqlConnection.Close();
}
}
}
/// <summary>
/// Runs a read command, returning results built up iteratively from the <paramref name="rowReader"/>
/// </summary>
public static List<T> ExecuteRead<T>(string command, NpgsqlConnection connection, Func<NpgsqlDataReader, T> rowReader, IEnumerable<NpgsqlParameter> parameters = null)
{
parameters = parameters ?? Array.Empty<NpgsqlParameter>();
List<T> results = new List<T>();
using (NpgsqlCommand sqlCommand = new NpgsqlCommand(command, connection))
{
foreach (NpgsqlParameter parameter in parameters)
{
sqlCommand.Parameters.Add(parameter);
}
using (NpgsqlDataReader dataReader = sqlCommand.ExecuteReader())
{
while (dataReader.Read())
{
T result = rowReader(dataReader);
results.Add(result);
}
}
}
return results;
}
/// <summary>
/// Runs a read command, returning no results.
/// </summary>
public static void ExecuteRead(string command, NpgsqlConnection connection, Action<NpgsqlDataReader> rowReader, IEnumerable<NpgsqlParameter> parameters = null)
{
parameters = parameters ?? Array.Empty<NpgsqlParameter>();
using (NpgsqlCommand sqlCommand = new NpgsqlCommand(command, connection))
{
foreach (NpgsqlParameter parameter in parameters)
{
sqlCommand.Parameters.Add(parameter);
}
using (NpgsqlDataReader dataReader = sqlCommand.ExecuteReader())
{
while (dataReader.Read())
{
rowReader(dataReader);
}
}
}
}
}
}