本文主要介绍如何利用c#实现数据库的备份和还原:
1、数据库备份操作
if (MessageBox.Show("确定要备份数据库吗?", "提示框", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
saveFileDialog1.Filter = "数据库文件|*.bak";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string path = saveFileDialog1.FileName;
if (File.Exists(path))
{
File.Delete(path);//注意,这个步骤很重要,如果重复,在备份的数据,就会变成,
//你刚开始的数据,所以每次都要先删除.
}
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Close();
}
string backupstr = "backup database SMDB to disk='" + path + "';";
bool re = SQL.sqlcon(backupstr);//执行语句
MessageBox.Show("备份成功!");
}
}
2、数据库还原操作:
if (MessageBox.Show("确定要还原数据库吗?", "提示框", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
openFileDialog1.Filter = "数据库文件|*.bak";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string path = openFileDialog1.FileName;
string backupstr = "use master ";
string s1 = " ALTER DATABASE SMDB SET OFFLINE WITH ROLLBACK IMMEDIATE";
string s2 = " Restore Database SMDB From disk='" + path + "' with REPLACE";
string s3 = " ALTER DATABASE SMDB SET ONLINE WITH ROLLBACK IMMEDIATE";
string sSql = backupstr + s1 + s2 + s3;
SQL.sqlcon(sSql);//执行语句
MessageBox.Show("恢复成功!");
}
}
<责任编辑:计算机毕业设计网(http://www.xiaoniu168.com)>