Reputation: 21194
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
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
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
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