-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabase.cs
116 lines (97 loc) · 3.31 KB
/
Database.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/**
* Mark Sarasua
* Dr. Alrifai
* CS 4253
* Final Exam Alternative Project
* Database.cs
*
*/
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace ACMFinalExamProblem
{
internal class Database
{
private const string _Server = "LAPTOP-37A20S3C";
private const string _Database = "CrossWordPuzzles";
private const string _Table = "Puzzles";
private string _Sql_Connection = string.Empty;
private int _Puzzles = 0;
public Database()
{
try
{
_Sql_Connection = $"Data Source={_Server}; Initial Catalog={_Database}; Integrated Security=True;";
using(SqlConnection connection = new SqlConnection(_Sql_Connection))
{
connection.Open();
SqlCommand command = new SqlCommand
(
$"SELECT COUNT(*) FROM {_Table}",
connection
);
_Puzzles = (int)command.ExecuteScalar();
command.Dispose();
}
}
catch (Exception ex)
{
Console.WriteLine( ex.ToString() );
}
}
public List<Puzzle> LoadPuzzleData()
{
try
{
List<object> puzzle_data = new List<object>();
using(SqlConnection connection = new SqlConnection(_Sql_Connection))
{
connection.Open();
SqlCommand command = new SqlCommand
(
$"SELECT * FROM {_Table}",
connection
);
SqlDataReader data_reader = command.ExecuteReader();
while (data_reader.Read())
{
List<object> row = new List<object>();
for (int i = 0; i < data_reader.FieldCount; i++)
{
row.Add(data_reader.GetValue(i));
}
puzzle_data.Add(row);
}
data_reader.Close();
command.Dispose();
}
return ExtractPuzzlesFromQueryResults(puzzle_data);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
private List<Puzzle> ExtractPuzzlesFromQueryResults(List<object> query_results)
{
List<Puzzle> puzzles = new List<Puzzle>();
foreach (object row in query_results)
{
Puzzle puzzle = new Puzzle
{
Puzzles = $"{_Puzzles}",
P = (row as List<object>)[0].ToString(),
R = (row as List<object>)[1].ToString(),
C = (row as List<object>)[2].ToString(),
S = (row as List<object>)[3].ToString(),
Letters = (row as List<object>)[4].ToString(),
Words = (row as List<object>)[5].ToString(),
};
puzzles.Add(puzzle);
}
return puzzles;
}
}
}