从代码还原不起作用,并且不会提供任何错误

本文关键字:任何 错误 还原 代码 不起作用 | 更新日期: 2023-09-27 18:37:15

我很难用我的 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()

从代码还原不起作用,并且不会提供任何错误

您没有在任何地方执行该命令...尝试执行非查询!

例如

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