如何使用 SMO 备份 SQL localDB

How to backup SQL localDB with SMO

我正在尝试使用 SMO 备份 SQL localDB 数据库,但没有成功。 我的代码有什么问题?

progressBar.Value = 0;
SaveFileDialog sfd = new SaveFileDialog();
string stringCon = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\whdb.mdf;Integrated Security=True";
sfd.Filter = "Database backup files (*.bak)|*.bak";
sfd.Title = "Create Database Backup";
sfd.FileName = DateTime.Today.ToString("ddMMMyyyy") + ".bak";
if (sfd.ShowDialog() == DialogResult.OK)
{
    using (SqlConnection conn = new SqlConnection(stringCon))
    {
        ServerConnection servConn = new ServerConnection(conn);
        SqlConnection.ClearAllPools();
        conn.Open();
        servConn.Connect();
        try {
            Server serverdb = new Server(servConn);
            Backup backupdb = new Backup() { Action = BackupActionType.Database, Database="whdb"};
            backupdb.Devices.AddDevice(sfd.FileName, DeviceType.File);
            backupdb.Initialize = true;
            backupdb.Incremental = false;
            backupdb.SqlBackupAsync(serverdb);
            progressBar.Value = 100;
            conn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

这是我在 运行 时遇到的异常:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll Additional information: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.

我认为问题在于您正在使用

 backupdb.SqlBackupAsync(serverdb);

在后台启动备份 运行。但是,当备份到达 运行 时,您已经关闭了连接。

您可以使用

  backupdb.SqlBackup(serverdb);

要不然去掉你的using and close,发现有的是备份后手动关闭连接。