如何以编程方式备份​​SQL Server 2014 Express Localdb(.mdf)文件

时间:2016-03-04 04:41:53

标签: c# sql-server sql-server-2014-localdb

我有一个简单的Windows应用程序,它使用SQL Server 2014 LocalDB(.mdf文件)。

我希望每当用户点击退出按钮时,我的应用程序会自动将其localdb文件(.mdf)备份到同一台用户计算机中的另一个文件夹。

我在下面写了简单的代码,但发生了SQLException语法错误:

  

'C:\ greendb_angelheart.mdf'

附近的语法不正确

DATABASE ""{0}""语法似乎很好)

我担心使用普通的localdb代码连接到特定的SqlConnection文件是否正确。

我的简单代码是:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    if (MessageBox.Show("Really want to exit? Thank you !", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No)
    {
            e.Cancel = true;
    }
    else
    {
            string backuppath_basic = @"c:\Green_Backup";

            if (!System.IO.Directory.Exists("backuppath_basic"))
            {
                System.IO.Directory.CreateDirectory(backuppath_basic);
            }

            var greendbfileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), string.Format("greendb_{0}.mdf", personID));
            var copied_greendbfileName = string.Format(@"C:\greendb_{0}.mdf", personID);

            string localConnectionString = string.Format(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename= " + Environment.GetEnvironmentVariable("APPDATA") + @"\greendb_{0}.mdf;Integrated Security=True;Connect Timeout=30;", personID);

            SqlConnection backupConn = new SqlConnection();
            backupConn.ConnectionString = localConnectionString;
            backupConn.Open();

            SqlCommand backupcomm = backupConn.CreateCommand();
            string backupdb = @"BACKUP DATABASE ""{0}"" TO DISK '{1}'";
            backupdb = string.Format(backupdb, greendbfileName, copied_greendbfileName);

            SqlCommand backupcreatecomm = new SqlCommand(backupdb, backupConn);
            backupcreatecomm.ExecuteNonQuery();

            backupConn.Close();

            Environment.Exit(0);
        }
    }

2 个答案:

答案 0 :(得分:0)

经过多次试验和分析,我终于解决了。对于正在寻找解决方案的人,我与我分享如下。

似乎使用MS SQL Localdb开发的人数比其他数据库少。

数据库的名称不必包含像.mdf这样的扩展名,等号=必须在一起作为DISK =

string backupdb = string.Format(@“BACKUP DATABASE greendb_ {0} TO DISK ='c:\ Green_Backup \ _ greendb_ {0} .bak'”,personID);

答案 1 :(得分:0)

它可能对某人有帮助。

备份

try
{
    var dlg = new System.Windows.Forms.FolderBrowserDialog();
    var result = dlg.ShowDialog(this.GetIWin32Window());

    if (result.ToString() == "OK")
    {
        var dbfileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LibraryManger.mdf");
        var backupConn = new SqlConnection { ConnectionString = eb.GetConnectionString() };
        backupConn.Open();

        var backupcomm = backupConn.CreateCommand();
        var backupdb = $@"BACKUP DATABASE ""{dbfileName}"" TO DISK='{Path.Combine(dlg.SelectedPath,"LibraryManagement.bak")}'";
        var backupcreatecomm = new SqlCommand(backupdb, backupConn);
        backupcreatecomm.ExecuteNonQuery();
        backupConn.Close();

        MessageBox.Show($"Database backup has successfully stored in {Path.Combine(dlg.SelectedPath, "LibraryManagement.bak")}", "Confirmation");
    }
}
catch (Exception ex)
{
    if(ex.Message.Contains("Operating system error"))
    {
        MessageBox.Show("Please chose a public folder.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
    else
        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

恢复

在恢复之前,您必须关闭现有连接

try
{
    if (eb != null)
    {
        eb.DisposeConnection();
        eb = null;
    }

    var dlg = new OpenFileDialog();
    dlg.InitialDirectory = "C:\\";
    dlg.Filter = "Database file (*.bak)|*.bak";
    dlg.RestoreDirectory = true;

    if (Equals(dlg.ShowDialog(), true))
    {
        using (var con = new SqlConnection())
        {
            con.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;Database=Master;Integrated Security=True;Connect Timeout=30;";
            con.Open();
            var dbfileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LibraryManger.mdf");
                using (var cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = $@"RESTORE DATABASE ""{dbfileName}"" FROM DISK='{dlg.FileName}'";

                    cmd.ExecuteNonQuery();
                }
                con.Close();
            }

        MessageBox.Show($"Database backup has successfully restored.", "Confirmation");
        eb = new EntityBroker.EntityBroker();
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}