尝试获取备份c#localdb时出错

时间:2017-02-19 15:08:17

标签: c# localdb

我试图恢复数据库,但是我收到了错误 数据库不存在我不知道我整天尝试的问题是什么,但我找不到任何有用的代码我尝试了很多代码所有给同样的错误请帮帮我

tring master_ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;Database=Master;Integrated Security=True;Connect Timeout=30;";
        string database = GetDataDirectory();
        MessageBox.Show(database);
        using (SqlConnection masterdbConn = new SqlConnection())
        {
            masterdbConn.ConnectionString = master_ConnectionString;
            masterdbConn.Open();

            using (SqlCommand multiuser_rollback_dbcomm = new SqlCommand())
            {
                multiuser_rollback_dbcomm.Connection = masterdbConn;
                multiuser_rollback_dbcomm.CommandText = @"ALTER DATABASE @DBNAME SET MULTI_USER WITH ROLLBACK IMMEDIATE";
                multiuser_rollback_dbcomm.Parameters.AddWithValue("@DBNAME",database);
                multiuser_rollback_dbcomm.ExecuteNonQuery();
            }
            masterdbConn.Close();
        }

        //SqlConnection.ClearAllPools();

        //using (SqlConnection backupConn = new SqlConnection())
        //{
        //    backupConn.ConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\BbCon.mdf;Integrated Security=True;Connect Timeout=30;";
        //    backupConn.Open();

        //    using (SqlCommand backupcomm = new SqlCommand())
        //    {
        //        backupcomm.Connection = backupConn;
        //        backupcomm.CommandText = @"BACKUP DATABASE BbCon TO DISK='c:\yourdbname.bak'";
        //        backupcomm.Parameters.AddWithValue("@DBNAME", database);
        //        backupcomm.ExecuteNonQuery();
        //    }
        //    backupConn.Close();
        //}

数据库名称是BbCon.mdf它位于C:\ Users \ asus \ Desktop \ New Folder(3)\ bbcon_accout_software \ bbcon_accout_software \ bin \ x86 \ Debug

enter image description here

1 个答案:

答案 0 :(得分:2)

请尝试以下代码

public string constring = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyDataBase.mdf;Integrated Security=True";

try
{ 
 SaveFileDialog sd = new SaveFileDialog();
 sd.Filter = "SQL Server database backup files|*.bak";
 sd.Title = "Create Database Backup";
 sd.FileName = "MyDataBase-" + string.Format("{0:dd-MM-yyyy_hh-mm-ss-tt}", DateTime.Now);

 if (sd.ShowDialog() == DialogResult.OK)
 {
  using (bcon = new SqlConnection(constring))
  {
   string sqlStmt = string.Format("backup database [" + System.Windows.Forms.Application.StartupPath + "\\MyDataBase.mdf] to disk='{0}'", sd.FileName);
   using (SqlCommand bu2 = new SqlCommand(sqlStmt, bcon))
   {
    bcon.Open();
    bu2.ExecuteNonQuery();
    bcon.Close();
    MessageBox.Show("Backup Created Sucessfully");
   }
  }
 }
}
catch (Exception){MessageBox.Show("Backup Not Created");}

尝试按照我的建议更改连接字符串,但仍然无法使用上面的代码。这对我来说就像魅力一样。