从Windows窗体应用程序通过一个按钮,点击备份SQL Server数据库 [英] Backup SQL Server database from windows form application by a button click
问题描述
我通过点击窗口申请表上的一个按钮需要备份数据库。我正在开发它在C#中的Visual Studio 2012中。
I need to backup a database by clicking a button on the windows application form. I'm developing it on Visual Studio 2012 in C#.
在Windows站点,我使用Transact SQL学会了备份。我试了一下在Visual Studio中的Transact SQL编辑器
In Windows site, I learned to backup using Transact SQL. I tried it from Transact SQL editor in visual studio.
下面是SQL的Transact我用:
Here is the SQL transact I used:
USE TestDB;
GO
BACKUP DATABASE TestDB
TO DISK = 'E:\aa.Bak'
WITH FORMAT,
MEDIANAME = 'Z_SQLServerBackups',
NAME = 'Full Backup of AdventureWorks2012';
GO
我想在C#中执行此。
I want to execute this in C#.
此外,每当我单击备份按钮,我想创建一个备份文件,并替换现有的备份文件。请问FORMAT参数不为此?
我能参数(位置,创建备份文件),在外部硬盘或笔设置到磁盘的某个位置开车吗?
Also whenever I click the backup button, I want to create a backup file and replace any existing backup file. Does the 'FORMAT' parameter does this purpose?
Can I set the parameter to disk (location where the backup file is created) to a location in an external hard disk or pen drive?
我可以按如下方式恢复DATABSE:
I can restore a databse as follows:
private void button4_restore(object sender, EventArgs e)<br/>
{
con.Open();<br/>
string str = "USE master;";<br/>
string str1= "ALTER DATABASE TestDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
string str3="RESTORE DATABASE TestDB FROM DISK = 'E:\\aa.Bak' ";<br/>
SqlCommand cmd = new SqlCommand(str, con);<br/>
SqlCommand cmd1 = new SqlCommand(str1, con);<br/>
SqlCommand cmd3 = new SqlCommand(str3, con);<br/>
cmd.ExecuteNonQuery();<br/>
cmd1.ExecuteNonQuery();<br/>
cmd3.ExecuteNonQuery();<br/>
MessageBox.Show("RECOVERED");<br/>
con.Close();
}
当我恢复这样,数据库将完全恢复到备份文件。有没有通过,我可以在附加.bak的数据与当前数据库中现有的数据文件的方法。
When I restore like this, the database is restored completely to the backup file. Is there a way by which I can append the data in .Bak file with the existing data in current database.
推荐答案
以下代码备份数据库'TESTDB'的文件'E.\backupfile.Bak如果按钮button_backup'被点击。
The following code backups the database 'TestDB' to the file 'E.\backupfile.Bak' if button 'button_backup' is clicked.
private void button_backup_Click(object sender, EventArgs e)
{
//con is the connection string
con.Open();
string str = "USE TestDB;";
string str1="BACKUP DATABASE TestDB TO DISK = 'E:\\backupfile.Bak' WITH FORMAT,MEDIANAME = 'Z_SQLServerBackups',NAME = 'Full Backup of Testdb';";
SqlCommand cmd1 = new SqlCommand(str, con);
SqlCommand cmd2 = new SqlCommand(str1, con);
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
MessageBox.Show("success");
con.Close();
}
这篇关于从Windows窗体应用程序通过一个按钮,点击备份SQL Server数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!