与正在进行的备份SQL Server数据库正在进行、备份、数据库、SQL

2023-09-03 11:03:14 作者:造化弄猪

有谁知道SQL如何备份服务器2005/2008数据库,C#和获取数据库备份进度?

Does anybody know how to backup SQL Server 2005/2008 database with C# and get the database backup progress?

推荐答案

下面是一个纯ADO.NET的解决方案,如果您有困难,在目标计算机上安装SMO / SQLDMO(它在后面的痛苦,如果你最好避免可以)。

Here's a pure ADO.NET solution, if you are having difficulty installing SMO/SQLDMO on the target machine (it's a pain in the behind, best avoided if you can).

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("'", "''") + "'";
}

统计= 1 子句告诉SQL Server发出严重性0的消息在指定的百分比时间(在这种情况下,1%)。该 FireInfoMessageEventOnUserErrors 属性和的InfoMessage 事件确保C#code。在执行过程中捕捉这些信息,而不是只结束。

The stats = 1 clause tells SQL Server to emit severity 0 messages at the specified percentage interval (in this case 1%). The FireInfoMessageEventOnUserErrors property and InfoMessage event ensure that the C# code captures these messages during execution rather than only at the end.