Thursday 20 February 2014

create database from script file

--> some time required when new user register on particular website that time
     create new database automatically  from script file.

--> script file:  script file is database creation  code you can create script file from your exist database using asp.net with c# code

    how to create script file , the step is following
    -->right click on your database (SQL server 2008 )
    -->select script database as
    -->select create and file to
    -->and open save as dialogue box set name and path where you want save this script file
    -->and click save
    -->then some process is done and  create script file in your download folder or where you set the path when open dialogue box

-->and you must be changes path in script file (open script file and remove or change the local computer path) other-wise your code  gives error

--> add following code in your code behind file

    -->required following namespace
------------------------------------------------------------------------------------------------
    using Microsoft.SqlServer.Management.Smo;
    using Microsoft.SqlServer.Management.Common;

    -->and create following function
------------------------------------------------------------------------------------------------
    public void CreateDatabaseFromScriptfile()
    {
     cn4 = new SqlConnection(@"Data Source=path\SQLEXPRESS,53286;Initial Catalog=databasename;User ID=sa;Password=pwd;");    //Connecrtion string
           string strdbname = "db_" + txtAccountName.Text; //this is for new databsase name
           FileInfo file = new FileInfo(Server.MapPath("Database_Code") + "\\" + "scriptFile.sql");
           //Here  path where your script file is store
           string strscript = file.OpenText().ReadToEnd();
           // in strscript string variable assign script code for replace the database name and execute server side
           string strupdatescript = strscript.Replace("[OldDatabaseName]", strdbname);
           // OldDatabaseName which is you set : when you create script file from which database , set this database name
           Server server = new Server(new ServerConnection(cn4));
           server.ConnectionContext.ExecuteNonQuery(strupdatescript);
          //this executed on server side and create new database , and this database name is value of strdbname

    }

--> above function take some more time for create new database on server side

--> and this function use on click event or any where which you want to

No comments:

Post a Comment



Asp.net tutorials