-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueryResults.cs
67 lines (58 loc) · 2.13 KB
/
QueryResults.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
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace RedknifeSQL
{
public class QueryResults
{
public string[] Headers { get; private set; }
public int[] LongestValues { get; private set; }
public List<string[]> Rows { get; private set; }
public QueryResults(SqlDataReader reader)
{
this.ExtractData(reader);
reader.Close();
}
private void ExtractData(SqlDataReader reader)
{
if (reader == null) throw new Exception("ERROR! Can't print table - reader is null");
if (reader.IsClosed) throw new Exception("ERROR! Can't print table - reader is closed");
if (!reader.HasRows)
{
this.Headers = new string[0];
this.LongestValues = new int[0];
this.Rows = new List<string[]>();
return;
}
// Set up the vars for data extraction
this.Headers = new string[reader.FieldCount];
this.LongestValues = new int[reader.FieldCount];
this.Rows = new List<string[]>();
bool parsedHeaders = false;
// Read the data from the reader
while (reader.Read())
{
if (!parsedHeaders)
{
// Parse the headers
for (int i = 0; i < reader.FieldCount; i++)
{
string header = reader.GetName(i);
this.Headers[i] = header;
this.LongestValues[i] = header.Length;
}
parsedHeaders = true;
}
// Extract each row
string[] row = new string[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
row[i] = reader.GetValue(i).ToString();
if (row[i].Length > this.LongestValues[i]) this.LongestValues[i] = row[i].Length;
}
// Add the row
this.Rows.Add(row);
}
}
}
}