我常常重灌系統,放在 D 槽的資料庫檔案每次都要在 SSMS 裡一個一個手動附加,十幾個庫點完非常耗時。於是寫了一個小程式:選一個資料夾,它會自動找出所有 .mdf,對應到各自的 .ldf,然後連上本機 MSSQL 逐一執行附加。
先跳出資料夾選擇對話框,用 DirectoryInfo.GetFiles("*.mdf") 收集主資料檔清單,再逐一推測日誌檔名稱並組出 sp_attach_db 指令。
/// <summary>
/// 循環查找指定目錄下要附加的資料庫檔與對應的日誌檔,
/// 連接本地資料庫並執行附加命令
/// </summary>
private void AttachFolderDB()
{
string strFileFolder = "";
FolderBrowserDialog myFolderBrowserDialog = new FolderBrowserDialog();
myFolderBrowserDialog.ShowDialog();
if (myFolderBrowserDialog.SelectedPath != "")
strFileFolder = myFolderBrowserDialog.SelectedPath;
// 找出所有的 MDF 檔
string[] arrAttachFilePath = null;
if (strFileFolder != "")
{
DirectoryInfo dir = new DirectoryInfo(strFileFolder);
FileInfo[] finfo = dir.GetFiles("*.mdf");
if (finfo.Length > 0)
{
arrAttachFilePath = new string[finfo.Length];
int i = 0;
foreach (FileInfo f in finfo)
{
arrAttachFilePath[i] = f.FullName;
i = i + 1;
}
}
}
// 循環附加
if (arrAttachFilePath != null)
{
for (int i = 0; i < arrAttachFilePath.Length; i++)
{
string strMdfFilePath = arrAttachFilePath[i].ToString();
string strLogFilePath = "";
string strLdfFilePath = "";
// 去掉副檔名,得到資料庫名稱
string strDataFileName = strMdfFilePath.Substring(
strMdfFilePath.LastIndexOf("\\") + 1,
strMdfFilePath.Length - strMdfFilePath.LastIndexOf("\\") - 1);
strDataFileName = strDataFileName.Remove(strDataFileName.LastIndexOf("."));
// 有些命名會多一截 "_Data",要先修掉
string logIndex = "_Data";
int n = strDataFileName.IndexOf(logIndex);
if (n == -1)
{
strLogFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\"))
+ "\\" + strDataFileName + "_log.ldf";
strLdfFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\"))
+ "\\" + strDataFileName + ".ldf";
}
else
{
strDataFileName = strDataFileName.Remove(strDataFileName.LastIndexOf("_"));
strLogFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\"))
+ "\\" + strDataFileName + "_log.ldf";
strLdfFilePath = strMdfFilePath.Remove(strMdfFilePath.LastIndexOf("\\"))
+ "\\" + strDataFileName + ".ldf";
}
StringBuilder sb = new StringBuilder();
sb.Append("sp_attach_db @dbname='" + strDataFileName
+ "',@filename1='" + strMdfFilePath + "'");
if (System.IO.File.Exists(strLogFilePath))
{
sb.Append(",@filename2='" + strLogFilePath + "'");
AttachDataBase(sb.ToString());
}
else if (System.IO.File.Exists(strLdfFilePath))
{
sb.Append(",@filename2='" + strLdfFilePath + "'");
AttachDataBase(sb.ToString());
}
else
{
Console.WriteLine("資料庫檔案 " + strMdfFilePath + " 缺少必備的日誌檔!");
}
}
}
}
用 Windows 整合式驗證連到本機 master 資料庫,執行上一段組好的指令;若同名資料庫已存在會拋出例外,這裡直接印出訊息而中斷該筆。
/// <summary>
/// 連接資料庫並執行附加命令
/// </summary>
/// <param name="strSql">附加資料庫命令字串</param>
private bool AttachDataBase(string strSql)
{
SqlConnection con = new SqlConnection(
@"Data Source=(local);Initial Catalog=master;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = strSql;
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
// 若已存在同名資料庫,這裡會收到例外
Console.WriteLine("附加資料庫時異常:" + ex.Message);
return false;
}
finally
{
con.Close();
}
}
SqlCommand 的參數化寫法會安全得多。sp_attach_db 已被標記為不建議使用,新版本可改用 CREATE DATABASE ... FOR ATTACH。dir.GetFiles() 一次取出所有 .mdf/.ndf/.ldf,以檔名主體分組,再動態組出多組 @filenameN。