-
Notifications
You must be signed in to change notification settings - Fork 0
/
DbInfo.cs
74 lines (67 loc) · 1.59 KB
/
DbInfo.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
using System;
using System.Data.SqlClient;
namespace CopyDb
{
class DbInfo
{
public string Server;
public string Database;
public string Username;
public string Password;
public DbInfo (string arg)
{
string[] parts = arg.Split(';');
if (parts.Length < 1)
throw new ArgumentException("Argument is not in the format Server;Database[;Username;Password]");
if (parts.Length < 2)
{
Server = ".";
Database = parts[0];
}
else
{
Server = parts[0];
Database = parts[1];
}
if (parts.Length >= 4)
{
Username = parts[2];
Password = parts[3];
}
}
public string ConnectionString
{
get
{
string cnstr = "Server=" + Server;
if (Username == null)
cnstr += ";Integrated Security=true";
else
cnstr += ";User ID=" + Username + ";Password=" + Password;
return cnstr;
}
}
public SqlConnection ConnectToExistingDatabase ()
{
SqlConnection cn = new SqlConnection(ConnectionString);
cn.Open();
cn.ChangeDatabase(Database);
return cn;
}
public void CreateDatabase(bool deleteExisting)
{
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
cn.Open();
if (deleteExisting)
using (
SqlCommand cmd =
new SqlCommand(
"if exists (select * from sys.databases where name='" + Database + "') drop database [" + Database + "]", cn))
cmd.ExecuteNonQuery();
using (SqlCommand cmd = new SqlCommand("create database [" + Database + "]", cn))
cmd.ExecuteNonQuery();
}
}
}
}