2012-06-13 38 views
0

我很難用我的C#腳本恢復幾個數據庫。它也沒有提供任何錯誤 - 它什麼都不做。從代碼還原不起作用,並提供沒有錯誤

下面的代碼:

// Connect to SQL Server 
SqlConnection conn = new SqlConnection("Data Source=SERVERNAME;" + "Integrated Security=SSPI;" + "Connection timeout=60"); 

StreamWriter logFile = new StreamWriter(@"F:\Backups\log.txt"); 

try{ 
    conn.Open(); 
}catch(Exception e){ 
    string errorTxt = "There was an error connecting to the server: " + e.ToString(); 
    logFile.WriteLine(errorTxt); 
} 

// Get Directory 
DirectoryInfo source = new DirectoryInfo(@"F:\Backups\SERVERNAME\"); 

foreach(FileInfo fi in source.GetFiles()){ 

    // We need to get the DB name: 
    string filename = fi.Name.ToString(); 
    int bkpIndex = filename.IndexOf("_backup"); 

    string sql = "USE master RESTORE DATABASE " + filename.Substring(0, bkpIndex) + " FROM DISK = '" + fi.FullName + "' WITH REPLACE"; 

    try{ 
     Console.WriteLine("Restoring {0}.", filename.Substring(0, bkpIndex)); 
     logFile.WriteLine("SQL: {0}", sql); 
     SqlCommand cmd = new SqlCommand(sql, conn); 
    }catch(Exception ex){ 
     logFile.WriteLine("Error restoring {0}: " + ex.ToString(), filename.Substring(0, bkpIndex)); 
    } 

} 

logFile.Close() 
conn.Close() 
+0

當你調試它 - 它執行命令嗎?日誌文件是否會刷新到磁盤或者是否出錯? –

回答

1

你沒有在任何地方執行命令嘗試的ExecuteNonQuery!

例如

SqlCommand cmd = new SqlCommand(sql, conn); 
cmd.ExecuteNonQuery(); 
+0

就是這樣......雖然很奇怪。我以爲我嘗試過,並要求提供一個參數......也許我點擊了不同的智能感知標籤或其他東西...... – user973259

相關問題