如何使用此连接字符串备份数据库

时间:2016-01-10 08:18:32

标签: c# sql-server database connection backup

我的连接字符串是:

 @"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + Application.StartupPath + @"\DataDirectory\sch.mdf;Integrated Security=True"

如何在C#Windows窗体应用程序中备份此数据库?

1 个答案:

答案 0 :(得分:0)

       folderBrowserDialog1.ShowDialog();

        string path1 = folderBrowserDialog1.SelectedPath;
        //MessageBox.Show(path1);
        DateTime dmiladi = DateTime.Now;
        PersianCalendar p = new PersianCalendar();

        string strdate = p.GetYear(dmiladi).ToString() + "/" + p.GetMonth(dmiladi).ToString() + "/" + p.GetDayOfMonth(dmiladi).ToString();

        string BackUpLocation = path1;
        string BackUpFileName = "backup_sch";
        string DatabaseName = Application.StartupPath + @"\DataDirectory\sch.mdf";
        string ServerName = "(LocalDB)\\v11.0";
        DatabaseName = "[" + DatabaseName + "]";
        string fileUNQ = p.GetYear(dmiladi).ToString() + "_" + p.GetMonth(dmiladi).ToString() + "_" + p.GetDayOfMonth(dmiladi).ToString() + "_time" + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString();

        BackUpFileName = BackUpFileName + fileUNQ + ".bak";
        string SQLBackUp = @"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + BackUpLocation + @"\" + BackUpFileName + @"'";

        string svr = "Server=" + ServerName + ";Database=master;Integrated Security=True";
        SqlConnection cnBk;
        SqlCommand cmdBkUp;
        cnBk = new SqlConnection(svr);

        cmdBkUp = new SqlCommand(SQLBackUp, cnBk);

        cnBk.Open();
        cmdBkUp.ExecuteNonQuery();