

界面如上,记得加上一个OpenFileDialog控件(ofd)和SaveFileDialog控件(sd)
代码如下:(图1的代码)
//图1代码
#region 点击备份按钮
private void btnBackup_Click(object sender, EventArgs e)
{
string Str_dar = "";
Str_dar = txtDefaultWay.Text.Trim().ToString();//备份路径
if (txtDefaultWay.Text == "")
{
MessageBox.Show("请选择备份数据库文件的路径。");
return;
}
try
{
Str_dar = "backup database DB_MovieFilm to disk='" + Str_dar + "'";
sqlhelper.getcomnum(Str_dar);//执行SQL语句
MessageBox.Show("数据备份成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
#region 点击备份路径按钮
private void btnWay_Click(object sender, EventArgs e)
{
sd.InitialDirectory = Application.StartupPath + "\\";//默认路径为D://
sd.Filter = "备份文件 (*.bak)|*.bak|所有文件 (*.*)|*.*";//筛选器,定义文件类型
sd.FilterIndex = 1; //默认值为第一个
sd.RestoreDirectory = true; //重新定位保存路径
if (sd.ShowDialog() == DialogResult.OK)
{
txtDefaultWay.Text = sd.FileName.ToString();//文本框的内容=路径
}
}
#endregion
#region 点击备份数据库的取消按钮
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion//图2
#region 点击还原路径按钮
private void btnRestoreWay_Click(object sender, EventArgs e)
{
ofd.InitialDirectory = Application.StartupPath + "\\";
ofd.Filter = "(*.bak)|*.bak|(所有文件)|*.*";
ofd.FilterIndex = 1;
ofd.RestoreDirectory = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
txtWay.Text = ofd.FileName.ToString();//文本框的内容=路径
}
}
#endregion
#region 点击还原按钮
private void btnRestore_Click(object sender, EventArgs e)
{
if (txtWay.Text == "")
{
MessageBox.Show("请选择备份数据库文件的路径。");
return;
}
try
{
string P_Str_cmdtxt = "USE master DECLARE tb CURSOR LOCAL FOR SELECT 'Kill '+ CAST(Spid AS VARCHAR) FROM master.dbo.sysprocesses";
P_Str_cmdtxt += " WHERE dbid=DB_ID('DB_MovieFilm') DECLARE @s nvarchar(1000) OPEN tb FETCH tb INTO @s";
P_Str_cmdtxt += " WHILE @@FETCH_STATUS = 0 BEGIN EXEC (@s) FETCH tb INTO @s END CLOSE tb DEALLOCATE tb";
P_Str_cmdtxt += " RESTORE DATABASE DB_MovieFilm FROM disk='" + txtWay.Text + "'";
SqlConnection sqlcon = sqlhelper.getcon();//数据库连接
sqlcon.Close();//关闭数据库
sqlcon.Open();//重新打开数据库
SqlCommand sqlcom = new SqlCommand(P_Str_cmdtxt, sqlcon);
sqlcom.ExecuteNonQuery();
MessageBox.Show("数据还原成功!", "提示框", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
}
MessageBox.Show("为了避免数据丢失,在数据库原还后将关闭整个系统。");
Application.Exit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion运行还原的时候,还是会出错,错误如下:
尚未备份数据库 "DB_MovieFilm" 的日志尾部。如果该日志包含您不希望丢失的工作,请使用 BACKUP LOG WITH NORECOVERY 备份该日志。请使用 RESTORE 语句的 WITH REPLACE 或 WITH STOPAT 子句来只覆盖该日志的内容。
解决如下:

将恢复模式的完整改为简单即可
附:恢复模式 说明
简单 不用备份的事务日志,即可还原
用于小型数据库和不经常更改的数据库
完整 所有事务都被记录到日志中
保留所有日志,直到事务日志备份
用于生产数据库
大容量日志 完整恢复模式的补充
不将大容量日志操作写入日志

被折叠的 条评论
为什么被折叠?



