随着进度备份SQL Server数据库

时间:2010-06-29 15:26:49

标签: c# .net sql-server

有人知道如何使用C#备份SQL Server 2005/2008数据库并获得数据库备份进度吗?

3 个答案:

答案 0 :(得分:29)

这是一个纯ADO.NET解决方案,如果您在目标计算机上安装SMO / SQLDMO时遇到困难(如果可以的话,最好避免使用它)。

public void BackupDatabase(SqlConnection con, string databaseName, string backupName, string backupDescription, string backupFilename) {
    con.FireInfoMessageEventOnUserErrors = true;
    con.InfoMessage += OnInfoMessage;
    con.Open();
    using(var cmd = new SqlCommand(string.Format(
        "backup database {0} to disk = {1} with description = {2}, name = {3}, stats = 1",
        QuoteIdentifier(databaseName),
        QuoteString(backupFilename),
        QuoteString(backupDescription),
        QuoteString(backupName)), con)) {
        cmd.ExecuteNonQuery();
    }
    con.Close();
    con.InfoMessage -= OnInfoMessage;
    con.FireInfoMessageEventOnUserErrors = false;
}

private void OnInfoMessage(object sender, SqlInfoMessageEventArgs e) {
    foreach(SqlError info in e.Errors) {
        if(info.Class > 10) {
            // TODO: treat this as a genuine error
        } else {
            // TODO: treat this as a progress message
        }
    }
}

private string QuoteIdentifier(string name) {
    return "[" + name.Replace("]", "]]") + "]";
}

private string QuoteString(string text) {
    return "'" + text.Replace("'", "''") + "'";
}

stats = 1子句告诉SQL Server以指定的百分比间隔(在本例中为1%)发出严重性为0的消息。 FireInfoMessageEventOnUserErrors属性和InfoMessage事件确保C#代码在执行期间而不是仅在结束时捕获这些消息。

答案 1 :(得分:2)

答案 2 :(得分:1)

这是MSDN使用SMO的some codeThis link解释了如何监控进度。