How To Create a SQL Server Database Programmatically by Using ADO.NET in Asp.Net? |
|
Answered By
Moderator1
on
12/24/2009 9:28:04 PM |
|
|
|
|
Hi,
Creating SQL Database dynamically through Asp.Net Program is very simple. Please follow the steps,
Step 1: Add System.Data.SqlClient to your aspx.cs file as follows,
using System.Data.SqlClient;
Step 2: Add a textbox and button control in your aspx and then add below code in the button click event. Make proper validation for the database name.
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text.Trim() == string.Empty) return;
string strDbCreate;
SqlConnection sqlconn = new SqlConnection("Server=localhost; Uid=xxxx; Pwd=xxxx; database=master");
strDbCreate = "CREATE DATABASE " + TextBox1.Text + " ON PRIMARY " +
"(NAME = " + TextBox1.Text + "_Data, " +
"FILENAME = 'D:\\" + TextBox1.Text + "Data.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = " + TextBox1.Text + "_Log, " +
"FILENAME = 'D:\\" + TextBox1.Text + ".ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand cmd = new SqlCommand(strDbCreate, sqlconn);
try
{
sqlconn.Open();
cmd.ExecuteNonQuery();
Response.Write("DataBase is Created Successfully");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cmd.Dispose();
if (sqlconn.State == ConnectionState.Open)
{
sqlconn.Close();
sqlconn.Dispose();
}
}
}
Good luck. |
|
|
|