Wednesday, December 3, 2008

Create Database and tables using C# code

This is the sample code to create database and its tables, Views and SP.

string conStr = "Data Source=server_name; Initial Catalog=Master; User ID=dummy; Password=dummy;";
FileInfo fileInfo = new FileInfo(@"C:\1.sql");
string script = fileInfo.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("select [name] from sys.databases", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
List databaseList = new List();
while (dr.Read())
{
databaseList.Add(dr[0].ToString());
}
conn.Close();
if (databaseList.Contains("TestDB1"))
{
MessageBox.Show("Database already exists.");
}
else
{
cmd = new SqlCommand("Create Database TestDB1", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conStr = "Data Source=server_name; Initial Catalog=TestDB1; User ID=dummy; Password=dummy;";
conn = new SqlConnection(conStr);
cmd = new SqlCommand(script, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Database created successfully.");
}

No comments: