D.R.
D.R.

Reputation: 21194

Simplest way to create database from connection string?

We're looking for a hands-on way to create a database from a given connection string with minimum code possible (e.g., to include in LINQPad scripts or C# scriptlets).

Is there a one-liner or something similar to create a database from a connection string? Most preferably something like "Static.CreateDatabase("connection string").

Upvotes: 2

Views: 3201

Answers (3)

pawel wujczyk
pawel wujczyk

Reputation: 521

Download nuget add as a reference to LINQPad.

Then use comand:

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

Upvotes: 0

vikas singh aswal
vikas singh aswal

Reputation: 202

I have created a static class Scripts which contains a static method 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;
        }

    }

Upvotes: 3

Igor Gorjanc
Igor Gorjanc

Reputation: 555

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

Upvotes: 0

Related Questions