从连接字符串创建数据库的最简单方法?

时间:2016-01-27 11:57:37

标签: c# .net sql-server

我们正在寻找一种实用的方法,以尽可能少的代码从给定的连接字符串创建数据库(例如,包含在LINQPad脚本或C#scriptlet中)。

是否有单行或类似的东西从连接字符串创建数据库?最优选的是"Static.CreateDatabase("connection string")

3 个答案:

答案 0 :(得分:3)

我创建了一个静态类Scripts,它包含一个静态方法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;
        }

    }

答案 1 :(得分:0)

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();
    }
}

答案 2 :(得分:0)

下载nuget作为reference添加到LINQPad。

然后使用comand:

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