110,920
社区成员
发帖
与我相关
我的任务
分享
百度上找了很多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();
}
}
这是一个示例,你先运行,路径替换成bak文件的实际路径。
显示出来的LogicName就是逻辑文件名。
我的脚本中的 test, test_log 这块要替换成你执行后显示出来的这2个
RESTORE FILELISTONLY FROM DISK = 'd:\xxx.bak'
c#代码运行SQL Server脚本,怎么写?
这个与C#没什么关系,你应该在sqlserver版块来提问。
你可以在图形界面操作,获取到正确的脚本,然后根据正确的脚本放到C#之中。
下面的供你参考。
--备份
USE [master]
GO
BACKUP DATABASE SampleDB
TO DISK = 'd:\SampleDB.bak'
WITH FORMAT, COMPRESSION, STATS = 10
GO
--还原
ALTER DATABASE SampleDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
RESTORE DATABASE SampleDB FROM DISK = N'D:\SampleDB.bak' WITH FILE = 1
, MOVE N'test' TO N'D:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\test.mdf'
, MOVE N'test_log' TO N'D:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\test.ldf', NOUNLOAD, REPLACE, STATS = 5
ALTER DATABASE SampleDB SET MULTI_USER