简体   繁体   English

以编程方式创建数据库

[英]Create Database Programmatically

I am trying to create a database programmatically in C#. 我试图在C#中以编程方式创建数据库。 I have scripts for database creation which work fine when I run them from SQL Server Management Studio. 我有用于数据库创建的脚本,当我从SQL Server Management Studio运行它们时,它们可以正常工作。 However, when I run the same scripts from my C# application, the following error occurs: 但是,当我从C#应用程序运行相同的脚本时,会发生以下错误:

An unhandled exception of type 'Microsoft.SqlServer.Management.Common.ExecutionFailureException' occurred in Microsoft.SqlServer.ConnectionInfo.dll Microsoft.SqlServer.ConnectionInfo.dll中发生了类型为“ Microsoft.SqlServer.Management.Common.ExecutionFailureException”的未处理异常

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. 只是为了让您知道有ac#框架可以为您完成所有这些工作。 http://www.sharparchitecture.net/ it will build your DB and your data access layer from a OO model. http://www.sharparchitecture.net/它将通过OO模型构建数据库和数据访问层。

public string CreateDataBase(string ipAddress, string UserName, string Password,string DB_filepath) { 公共字符串CreateDataBase(字符串ipAddress,字符串UserName,字符串Password,字符串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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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