Pages

Thursday, October 10, 2013

Create SQL Database Dynamically using C# code

Use below Code to Create SQL Database and create .mdf and .ldf file to your desired location :

Note: In the connection string , Initial Catalog should be 'master'

'myDB' will be by any name , which u want to like as database name.



SqlConnection con = new SqlConnection("Data Source=yourservername;Initial Catalog=master;Integrated Security=True");
SqlCommand com = new SqlCommand();

string db_str = "CREATE DATABASE myDB ON PRIMARY " +
       "(NAME =
myDB _Data, " +
       "FILENAME = 'C:\\
myDB.mdf', " +
       "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
       "LOG ON (NAME =
myDB _Log, " +
       "FILENAME = 'C:\\
myDB.ldf', " +
       "SIZE = 1MB, " +
       "MAXSIZE = 5MB, " +
       "FILEGROWTH = 10%)";

con.Open();com.Connection = con;
com.CommandText = db_str;
com.ExecuteNonQuery();
con.Close();


After compile this Code:

Database myDB Created to the SQL, and myDB.mdf and myDB.ldf created in the C Drive as the path given in the code.


No comments:

Post a Comment