如何在C#中还原SQL Server 2012数据库.bak文件? [英] How to restore a SQL Server 2012 database .bak file in C#?

查看:263
本文介绍了如何在C#中还原SQL Server 2012数据库.bak文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了Windows窗体中的MIS,在其中我备份了SQL Server 2012数据库,但是无法还原备份(.bak)文件.

I have developed a MIS in Windows Forms in which I took backup of my SQL Server 2012 database, but I am unable to restore the backup (.bak) file.

这是我的代码:

private void buttonRestore_Click(object sender, EventArgs e)
{
    try
    {
        openFileDialog1.Filter = "Backup File |*.bak";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string sql = "Alter Database BOQ SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
            sql += "Restore Database BOQ FROM DISK ='" + openFileDialog1.FileName + "' WITH REPLACE;";

            SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=BOQ;Integrated Security=True");
            SqlCommand command = new SqlCommand(sql,con);

            con.Open();
            command.ExecuteNonQuery();

            MessageBox.Show("Database Recovered Successfully!");
            con.Close();
            con.Dispose();
        }
    }
    catch (Exception ex) 
    { 
         MessageBox.Show(ex.Message); 
    }
}

但是我得到这个错误:

推荐答案

无法连接到数据库BOQ,然后在其之上还原.bak

You cannot connect to your database BOQ and then restore a .bak over top of it!

"Data Source=.; Initial Catalog=BOQ;Integrated Security=True"
                                ****

您需要连接到master数据库,然后然后可以还原您的BOQ数据库:

You need to connect to the master database, and then you can restore your BOQ database:

"Data Source=.; Initial Catalog=master;Integrated Security=True"
                                *******

这篇关于如何在C#中还原SQL Server 2012数据库.bak文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆