SQL Server备份/还原进度指示器

时间:2019-06-08 16:02:29

标签: c# sql-server-2008

我有一个Windows窗体应用程序的备份和还原程序,对我来说很好。我需要将此代码放入线程或后台工作程序中,以显示已完成百分比的操作进度。下面是我的代码。任何帮助将不胜感激。

if (rdBackup.Checked)
{
    SaveFileDialog svdlg = new SaveFileDialog();
    svdlg.Filter = "Sql Server Database Backup File *.bak|*.bak";

    svdlg.ShowDialog();

    if (!string.IsNullOrEmpty(svdlg.FileName))
    {
        SqlConnection cn = new SqlConnection(Variables.ConStr);
        cn.Open();

        SqlCommand cmd = new SqlCommand();
        SqlDataReader reader;
        cmd.CommandText = @"BACKUP DATABASE [" + cn.Database.ToString() + "] TO DISK = '" + svdlg.FileName + "'";

        cmd.CommandType = CommandType.Text;
        cmd.Connection = cn;

        reader = cmd.ExecuteReader();
        cn.Close();

        MessageBox.Show("Database backup successful.");
    }
}
else
{
    btnBackupRestore.Text = "&Restore Database";

    OpenFileDialog opdlg = new OpenFileDialog();
    opdlg.Filter = "SQL Server Database Backup File *.bak|*.bak";

    opdlg.ShowDialog();

    if (!string.IsNullOrEmpty(opdlg.FileName))
    {
        SqlConnection cn = new SqlConnection(Variables.ConStr);
        cn.Open();

        SqlCommand cmd = new SqlCommand();
        SqlDataReader reader;
        cmd.CommandText = @"use master;ALTER DATABASE [" + cn.Database.ToString() + "] SET Single_User WITH Rollback Immediate;  " +
                 "RESTORE DATABASE [" + cn.Database.ToString() + "] FROM DISK = '" + opdlg.FileName + "'"
                 + "ALTER DATABASE [" + cn.Database.ToString() + "] SET Multi_User ";

        //cmd.CommandText = "DBCC CHECKDB ('[" + cn.Database.ToString() + "]')";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = cn;

        reader = cmd.ExecuteReader();

        cn.Close();

        MessageBox.Show("Database restored successfully.");
    }
}

1 个答案:

答案 0 :(得分:0)

如果您想捕获备份期间发送到SSMS窗口的10,20,30,40 ...消息并准备某种进度条以显示这些进展,则需要使用SMO libraries(Sql服务器管理对象)

下面的代码用于接收这些消息并执行备份

using(SqlConnection con = new SqlConnection(".......")) 
{
    ServerConnection svrConnection = new ServerConnection(con);
    Server server = new Server(svrConnection);
    Backup bk = new Backup();
    bk.PercentComplete += pctComplete;
    bk.Action = BackupActionType.Database;
    bk.Database = con.Database
    bk.Devices.Add(new BackupDeviceItem(svdlg.FileName, DeviceType.File));
    bk.SqlBackup(server);

}

void pctComplete(object server, PercentCompleteEventArgs e)
{
    Console.WriteLine(e.Percent);
}

还原操作类似