AspdotnetCodes.com
Search
Articles
Books
Resources
Asp.Net News
Downloads
Free Tech Magazines
Asp.Net Web Hosting
Archives
Softwares
Newsletter
Suggest Us
Link to Us
Feeds Subscription
Articles
Questions & Answers
Tips & Tricks
 create database dynamically in Asp.net?
Posted by shanmugapriya on  12/24/2009 12:06:53 AM Category: ADO.NET
Add to my favorites
Email to friend
How to create SQL database and table dynamically in Asp.net C#

Post Your Reply Post New Question

 Viewer's Reply
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.
 
Post Your Reply If you still have problem, post it again under this reply for better response.

 
Sponsored by
Introduction to Web Applications Development
Backup and Recovery Best Practices for Microsoft SQL Server 2005
Washington Technology