-
Notifications
You must be signed in to change notification settings - Fork 0
/
SqlHelper.cs
83 lines (75 loc) · 2.56 KB
/
SqlHelper.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
namespace CustomStorage.Web.React.SubmissionStorage
{
using System;
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
/// <summary>
/// Sql Helper for DB Interaction.
/// </summary>
public class SqlHelper : ISqlHelper
{
private readonly IConfiguration _configuration;
/// <summary>
/// Initializes a new instance of the <see cref="SqlHelper"/> class.
/// </summary>
public SqlHelper(IConfiguration configuration)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
private SqlConnection GetConnection()
{
return new SqlConnection(_configuration.GetConnectionString("EPiServerDB"));
}
private SqlCommand GetSqlCommand(SqlConnection connection, string query)
{
return new SqlCommand(query, connection);
}
/// <summary>
/// Use this method for all queries related to fetching of data.
/// </summary>
public DataTable GetDataRows(string query)
{
using var connection = this.GetConnection();
if (connection == null) return null;
using var command = this.GetSqlCommand(connection, query);
if (command == null) return null;
var da = new SqlDataAdapter(command);
var dt = new DataTable();
try
{
connection?.Open();
da?.Fill(dt);
connection?.Close();
}
catch (Exception ex)
{
// TODO need to figure out what comes here.
}
return dt;
}
/// <summary>
/// Use this method for all Execute non query operations.
/// </summary>
public int ExecuteNonQuery(string query)
{
using var connection = this.GetConnection();
if (connection == null) return -2;
using var command = this.GetSqlCommand(connection, query);
if (command == null) return -2;
int result;
try
{
connection.Open();
result = command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
// TODO need to figure out what comes here.
return -1;
}
return result;
}
}
}