简体   繁体   中英

Create Database Programmatically

I am trying to create a database programmatically in C#. I have scripts for database creation which work fine when I run them from SQL Server Management Studio. However, when I run the same scripts from my C# application, the following error occurs:

An unhandled exception of type 'Microsoft.SqlServer.Management.Common.ExecutionFailureException' occurred in Microsoft.SqlServer.ConnectionInfo.dll

Any ideas as to why this might be happening?

Just to let you know there is ac# frame work which will do all this for you. http://www.sharparchitecture.net/ it will build your DB and your data access layer from a OO model.

public string CreateDataBase(string ipAddress, string UserName, string Password,string DB_filepath) {

        Microsoft.SqlServer.Management.Smo.Server addDBserver = new     Microsoft.SqlServer.Management.Smo.Server(ipAddress);
        addDBserver.ConnectionContext.LoginSecure = false;
        addDBserver.ConnectionContext.Login = UserName;
        addDBserver.ConnectionContext.Password = Password;



        try
        {
            //*Crerate Databse*
            addDBserver.ConnectionContext.Connect();
            FileInfo filedb = new FileInfo(DB_filepath);
            string scriptdb = filedb.OpenText().ReadToEnd();
            string scriptdb1 = scriptdb.Replace("GO", Environment.NewLine);
            string scriptdb2 = scriptdb1.Replace("\r\nGO\r\n", "");
            addDBserver.ConnectionContext.ExecuteNonQuery(scriptdb2);
            addDBserver.ConnectionContext.Disconnect();
            string Msg;
                Msg = "db created successfully";
                return Msg;
            return true;


        }
        catch (Exception ex)
        {
       string Msg1 = "db notcreated successfully";
         return ex.Message;
           throw;
        }
    }
        //Database created Successfully

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM