远程创建数据库时,通过master(总是存在的一个数据库)数据库进行连接
static bool CreateDatabase(string strDBsource_, string strUserName_, string strUserPwd_, string strDBName_, string strPath_)
{
bool bSuccess = false;
try
{
char[] strTrim = {'//',' '};
strPath_ = strPath_.TrimEnd(strTrim);
// When Use in local, can create path auto; otherwise, make sure the path has existed.
//if (!Directory.Exists(strPath_))
// Directory.CreateDirectory(strPath_);
string strFile = strPath_ + @"/" + strDBName_;
string strSrc = "Data Source=" + strDBsource_ + ";Initial Catalog=Master;Persist Security Info=True;User ID=" +
strUserName_ + ";Password=" + strUserPwd_;
using (SqlConnection conMaster = new SqlConnection(strSrc))
{
conMaster.Open();
// Check if the Database has existed first
string strExist = @"select * from dbo.sysdatabases where name='" + strDBName_ + @"'";
SqlCommand cmdExist = new SqlCommand(strExist, conMaster);
SqlDataReader readerExist = cmdExist.ExecuteReader();
bool bExist = readerExist.HasRows;
readerExist.Close();
if( bExist )
{
string strDel = @"drop database " + strDBName_;
SqlCommand cmdDel = new SqlCommand(strDel, conMaster);
cmdDel.ExecuteNonQuery();
Console.WriteLine("Database has exists, and del now");
}
// Create the database now;
string strDatabase = "Create Database " + strDBName_ + " on Primary" +
"(" +
@"name=N'" + strDBName_ + @".mdf'," +
@"Filename=N'" + strFile + @".mdf'," +
"size=4096KB,Maxsize=UNLIMITED,FileGrowth=10%)" + // 数据库文件至少为3M
"Log on" +
"(" +
"Name=N'" + strDBName_ + "'," +
@"FileName=N'" + strFile + @".ldf'," +
"size=1024KB,Maxsize=UNLIMITED,FileGrowth=10%)" +
"Collate chinese_prc_Ci_as"; // 按中文格式排序
SqlCommand cmdCreate = new SqlCommand(strDatabase, conMaster);
cmdCreate.ExecuteNonQuery();
conMaster.Close();
}
Console.WriteLine("Create OK");
bSuccess = true;
}
catch (Exception e)
{
Console.WriteLine("Database failed: {0}", e.Message);
}
return bSuccess;
}