有人知道如何使用C#备份SQL Server 2005/2008数据库并获得数据库备份进度吗?
答案 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)
SMO有一个百分比完成事件。
答案 2 :(得分:1)