我有这个代码使用C#备份我的数据库。
但是我收到Backup Failed for Server ADMIN-PC
错误消息。
我可以从SQL Server Management Studio运行备份,但是由于某种原因它从这里给我这个错误。
我该如何做到这一点?
private void btnBackup_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
try
{
Server dbServer = new Server(new ServerConnection(txtServer.Text, txtUserName.Text, txtPassword.Text));
Backup dbBackup = new Backup() {Action = BackupActionType.Database, Database = txtDatabase.Text};
dbBackup.Devices.AddDevice(@"C:\PDM.bak", DeviceType.File);
dbBackup.Initialize = true;
dbBackup.PercentComplete += DbBackup_PercentComplete;
dbBackup.PercentComplete += DbBackup_Complete;
dbBackup.SqlBackupAsync(dbServer);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DbBackup_Complete(object sender, ServerMessageEventArgs e)
{
if (e.Error != null)
{
label5.Invoke((MethodInvoker)delegate
{
lblStatus.Text = e.Error.Message;
});
}
}
private void DbBackup_PercentComplete(object sender, PercentCompleteEventArgs e)
{
progressBar1.Invoke((MethodInvoker)delegate
{
progressBar1.Value = e.Percent;
progressBar1.Update();
});
label5.Text = $"{e.Percent}%";
}
}
答案 0 :(得分:1)
这是所有异常消息吗?只尝试没有进度条的备份工作,看看抛出了什么异常。没有完整的图片,这里的人不能帮助你。
您只需使用这种方式进行备份吗?
这是我备份数据库的代码供您参考。
using (SqlConnection masterdbConn = new SqlConnection())
{
masterdbConn.ConnectionString = localmasterConnectionString;
masterdbConn.Open();
using (SqlCommand rollback_dbcomm = new SqlCommand())
{
rollback_dbcomm.Connection = masterdbConn;
rollback_dbcomm.CommandText = "ALTER DATABASE mydbname SET MULTI_USER WITH ROLLBACK IMMEDIATE";
rollback_dbcomm.ExecuteNonQuery();
}
masterdbConn.Close();
}
SqlConnection.ClearAllPools();
using (SqlConnection backupConn = new SqlConnection())
{
backupConn.ConnectionString = localConnectionString;
backupConn.Open();
using (SqlCommand backupcomm = backupConn.CreateCommand())
{
backupcomm.CommandText = @"BACKUP DATABASE mydbname TO DISK='c:\mydbname.bak'";
backupcomm.ExecuteNonQuery();
}
backupConn.Close();
}
更改DATABASE ROLL BACK IMMEDIATE命令完成与数据库的所有未完成的事务,让我们说“从数据库中移开以准备备份。”
您需要检查connectionstring中的角色和权限..
您能在SQL Server Management Studio中显示要备份的SQL语法吗?和没有凭据的连接字符串(如密码)? 你能更详细地描述一下你的问题吗?
备份工作需要深入了解Sever的工作原理..