-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathScriptExecute.cs
105 lines (92 loc) · 2.92 KB
/
ScriptExecute.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
using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
namespace dbscript
{
class ScriptExecute
{
public bool success = false;
public string exception = "";
public int attempts = 0;
public string sql = "";
public string dbName = "";
public string script = "";
private bool abort = false;
public ScriptExecute(string sqlFile, string db, Connection conn)
{
sql = sqlFile;
dbName = db;
execute(conn);
}
public void execute(Connection conn)
{
// arguments for sqlcmd.exe utility
var args = String.Format(@" -S {0} -U {1} -P {2} -d {3} -i {4} ", conn.serverName, conn.username, conn.password, dbName, sql);
try
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "sqlcmd";
p.StartInfo.Arguments = args;
p.Start();
// waiting for exit makes this very slow
// but not waiting can cause memory overflow
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
success = true;
}
catch (Exception e)
{
success = false;
exception = e.ToString();
}
finally
{
attempts++;
}
}
// other method //
public ScriptExecute(string sqlFile, Database db)
{
sql = sqlFile;
execute(db);
}
public void execute(Database db)
{
if (abort == true) return;
StreamReader sr = new StreamReader(sql);
script = sr.ReadToEnd();
try
{
db.ExecuteNonQuery(script);
success = true;
}
catch (Microsoft.SqlServer.Management.Smo.FailedOperationException e)
{
success = false;
exception = e.InnerException.ToString();
}
/*
catch (OutOfMemoryException e)
{
success = false;
exception = e.ToString();
abort = true;
return;
}
*/
finally
{
if (success == false) Console.WriteLine("!failed...");
attempts++;
}
}
}
}