c#代码还原SQL Server数据库

货郎大叔 货郎大叔 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

百度上找了很多c#代码备份、还原SQL Server数据库的代码,都不好使。备份的时候,不能覆盖现有备份文件,还原的时候,也不能覆盖现有数据库。愿意有偿打赏。

下面是目前的代码,HeYueDbSet是数据库名称。

private string connectionString = "data source=.;Initial Catalog=master;integrated security=SSPI;";  //注意啊,这个数据库连接字符串是使用master系统数据库啊
private void Button_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
    saveFileDialog.Title = "备份数据库";
    saveFileDialog.Filter = "备份文件(*.bak)|*.bak";
    saveFileDialog.RestoreDirectory = true;
    if (saveFileDialog.ShowDialog() == true)
    {
        SqlConnection SqlConnection = new SqlConnection(connectionString);
        string Comtext = "BACKUP DATABASE HeYueDbSet TO DISK = '" + saveFileDialog.FileName + "'";
        SqlCommand SqlCommandBackup = new SqlCommand() { Connection = SqlConnection, CommandType = CommandType.Text, CommandText = Comtext };
        SqlConnection.Open();
        try
        {
            SqlCommandBackup.ExecuteNonQuery();
        }
        catch (Exception m)
        {
            string str = m.Message;
            SqlConnection.Close();
        }
        SqlConnection.Close();
    }
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
    openFileDialog.Title = "还原数据库";
    openFileDialog.Filter = "备份文件(*.bak)|*.bak";
    openFileDialog.RestoreDirectory = true;
    if (openFileDialog.ShowDialog() == true)
    {
        SqlConnection SqlConnection = new SqlConnection(connectionString);
        string Comtext = "Alter database HeYueDbSet Set Offline With rollback immediate RESTORE DATABASE HeYueDbSet FROM DISK = '" + openFileDialog.FileName + "'" + " Alter database HeYueDbSet Set Online With Rollback immediate";
        SqlCommand SqlCommandBackup = new SqlCommand() { Connection = SqlConnection, CommandType = CommandType.Text, CommandText = Comtext };
        SqlConnection.Open();
        try
        {
            SqlCommandBackup.ExecuteNonQuery();
        }
        catch (Exception m)
        {
            string str = m.Message;
            SqlConnection.Close();
        }
        SqlConnection.Close();
    }
}

 

...全文
评论 9
收藏 已收藏
分享
返回顶部
货郎大叔
C# 111,130 成员 642,541 内容