Repository navigation
Expand file tree
/
Copy pathDbManager.cs
More file actions
169 lines (131 loc) · 6.14 KB
/
Copy pathDbManager.cs
File metadata and controls
169 lines (131 loc) · 6.14 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace JBACodeTest
{
public class DbManager
{
internal string InsertData(string localDbPath, List<RainfallEntry> entries)
{
string result = "";
using (SqlConnection connection = new SqlConnection(MakeConnectionString(localDbPath)))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("InsertRainfall");
command.Connection = connection;
command.Transaction = transaction;
try
{
var start = DateTime.Now;
// create the table if it doesn't exist already
command.CommandText =
@"IF NOT (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'Precipitation'))
BEGIN
CREATE TABLE[dbo].[Precipitation]
(
[Xref] INT NOT NULL,
[Yref] INT NOT NULL,
[Date] DATE NOT NULL,
[Value] INT NOT NULL
)
END;";
command.ExecuteNonQuery();
// NB deleting all existing rows in the table - for this test example at least, allows it to be run multiple times and stops stuff accumulating in the DB
command.CommandText = "DELETE FROM Precipitation";
command.ExecuteNonQuery();
int blockSize = 200;
int i = 0;
while (i < entries.Count)
{
// write in blocks of N - this seems optimal but have not rigorously tested the alternatives
int block = Math.Min(entries.Count - i, blockSize);
command.CommandText = "INSERT INTO Precipitation([Xref], [Yref], [Date], [Value]) VALUES ";
for (int j = 0; j < block; ++j)
{
if (j > 0)
command.CommandText += ", ";
var e = entries[i + j];
command.CommandText += String.Format(" ('{0}', '{1}', '{2}', '{3}')", e._x, e._y, e._date.ToString("yyyy-MM-dd"), e._amount);
}
command.CommandText += ";";
command.ExecuteNonQuery();
i += block;
}
var end = DateTime.Now;
// Attempt to commit the transaction.
transaction.Commit();
TimeSpan span = end - start;
int ms = (int)span.TotalMilliseconds;
result = String.Format("Success - took {0}s", (float)(ms)/1000.0f);
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Commit Exception Type: {0}\nMessage: {1}", ex.GetType(), ex.Message));
result = "error committing";
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
MessageBox.Show(String.Format("Commit Exception Type: {0}\nMessage: {1}", ex2.GetType(), ex2.Message));
result = "error rolling back";
}
}
connection.Close();
}
return result;
}
private static string MakeConnectionString(string localDbPath)
{
return @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = " + localDbPath + @"; Integrated Security = True";
}
internal string Report(string localDbPath, int x, int y)
{
string result = "Test:\r\n";
using (SqlConnection connection = new SqlConnection(MakeConnectionString(localDbPath)))
{
SqlCommand command = connection.CreateCommand();
command.Connection = connection;//?
try
{
connection.Open();
command.CommandText = "SELECT COUNT(*) FROM Precipitation; ";
Int32 count = (Int32)command.ExecuteScalar();
result += String.Format("Table contains {0} rows\r\n", count);
result += String.Format("First 24 rows at {0},{1}:\r\n",x,y);
command.CommandText = String.Format("SELECT TOP 24 * FROM Precipitation WHERE Xref = {0} AND Yref = {1}", x, y);// "SELECT * FROM Precipitation LIMIT 0,10;";
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
result += String.Format("{0}, {1}, {2}, {3}\r\n", reader["Xref"], reader["Yref"], reader["Date"], reader["Value"]);
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format("DB Exception Type: {0}\nMessage: {1}", ex.GetType(), ex.Message));
}
connection.Close();
}
return result;
}
}
}