簡體   English   中英

從連接字符串創建數據庫的最簡單方法?

[英]Simplest way to create database from connection string?

我們正在尋找一種實用的方法,用盡可能少的代碼(例如,包含在 LINQPad 腳本或 C# 腳本中)從給定的連接字符串創建數據庫。

是否有單行或類似的東西來從連接字符串創建數據庫? 最好是像"Static.CreateDatabase("connection string")

我創建了一個靜態類腳本,其中包含一個靜態方法 CreateDatabase

// USE Class Like this
Scripts.CreateDatabase("Connectionstring")

//Class
static class Scripts
    {

        static bool CreateDatabase(string Connectionstr)
        {
            bool result =false;

              SqlConnection Conn = new SqlConnection(Connectionstr); // pass connection string and user must have the permission to create a database,

              string Query = "CREATE DATABASE Exampledatabase ";
                SqlCommand Command = new SqlCommand(Query, Conn);
                try
                {
                    Conn .Open();
                    Command.ExecuteNonQuery();
                    result =true;
                }
                catch (System.Exception ex)
                {
                    result =false;
                }
                finally
                {
                    if (Conn.State == ConnectionState.Open)
                    {
                        Conn.Close();
                    }
                }
            return result;
        }

    }
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");
String sql = "CREATE DATABASE MyDatabase";
SqlCommand myCommand = new SqlCommand(sql, myConn);
try {
    myConn.Open();
    myCommand.ExecuteNonQuery();
    // OK
} catch (System.Exception ex) {
    // failed
} finally {
    if (myConn.State == ConnectionState.Open) {
        myConn.Close();
    }
}

下載nuget add 作為對 LINQPad 的參考

然后使用命令:

void Main()
{
    var database = new ProductivityTools.CreateSQLServerDatabase.Database("XXX", "Server=.\\SQL2019;Trusted_Connection=True;"); 
    database.Create();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM