C#数据库备份、还原
来源:本站原创
作者:管理员
添加时间:2011-05-27
点击数:1941
1、相关介绍:
以下是引用片段: private void 备份数据库ToolStripMenuItem_Click(object sender, EventArgs e) { 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 StuBody to disk='" + path + "';"; SqlConnection sql = new SqlConnection(Stu_add.Sqlstr); SqlCommand sqlc = new SqlCommand(backupstr, sql); try { sql.Open(); sqlc.ExecuteNonQuery(); MessageBox.Show("备份成功!"); sql.Close(); } catch (Exception ex) { string stringError = ex.ToString(); MessageBox.Show("备份失败!"); sql.Close(); } } } }
|
以下是引用片段: private void 还原数据库ToolStripMenuItem_Click(object sender, EventArgs e) { if (MessageBox.Show("确定要还原数据库吗?", "提示框", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { openFileDialog1.Filter = "数据库文件|*.bak"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { string path = openFileDialog1.FileName; SqlConnection sql = new SqlConnection(Stu_add.Sqlstr); string backupstr = "use master "; string s1 = "ALTER DATABASE StuBody SET OFFLINE WITH ROLLBACK IMMEDIATE"; string s2 = "Restore Database StuBody From disk='" + path + "' with REPLACE"; string s3 = "ALTER DATABASE StuBody SET ONLINE WITH ROLLBACK IMMEDIATE"; try { SqlCommand sqlc = new SqlCommand(backupstr, sql); sql.Open(); sqlc.ExecuteNonQuery(); sqlc = new SqlCommand(s1, sql); sqlc.ExecuteNonQuery(); sqlc = new SqlCommand(s2, sql); sqlc.ExecuteNonQuery(); sqlc = new SqlCommand(s3, sql); sqlc.ExecuteNonQuery(); MessageBox.Show("恢复成功!"); sql.Close(); } catch (Exception ex) { string stringError = ex.ToString(); MessageBox.Show("恢复失败!"); sql.Close(); } } } }
|
<责任编辑:计算机毕业设计网(http://www.xiaoniu168.com)>