我们正在寻找一种实用的方法,以尽可能少的代码从给定的连接字符串创建数据库(例如,包含在LINQPad脚本或C#scriptlet中)。
是否有单行或类似的东西从连接字符串创建数据库?最优选的是"Static.CreateDatabase("connection string")
。
答案 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)