C#备份数据和还原数据

 
  
  private void button1_Click(object sender, EventArgs e)
{
//选择要备份的路径
this.folderBrowserDialog1.ShowDialog();
this.txtDbBackup.Text = folderBrowserDialog1.SelectedPath;
}

private void btnChooseOK_Click(object sender, EventArgs e)
{

if (txtDbhuanyuan.Text=="")
{
//路径+数据库名字
string name = txtDbBackup.Text+@"\QMX.mdf";
//备份数据库语句
string sql = string.Format(@"Backup Database QMX To disk='{0}'",name);


if (DBHelpers.Upadate(sql)) {
MessageBox.Show("备份成功");


}
else
{
MessageBox.Show("备份失败");
}
}
else
{
MessageBox.Show("请选择路径");
}



}
private void btnDeoxidizeTxt_Click(object sender, EventArgs e)
{
//选择要恢复的路径

string xiaohao;
OpenFileDialog op = new OpenFileDialog();
//默认打开D盘
op.InitialDirectory = "D:\\";
op.Filter = "(*.mdf)|*.mdf|(*.png)|*.png|(*.*)|*.*";
op.RestoreDirectory = true;
op.AddExtension = true;
if (op.ShowDialog()==DialogResult.OK)
{
xiaohao= op.FileName;

txtDbhuanyuan.Text = xiaohao;
}
}

private void btnDeoxidize_Click(object sender, EventArgs e)
{
if (txtDbhuanyuan.Text=="")
{
MessageBox.Show("请正确选择地址");
}
else
{
//恢复数据库sql语句
string sql = string.Format("if exists(select * from sysdatabases where name='QMX') drop database QMX use master restore database QMX from disk='{0}'", this.txtDbhuanyuan.Text);

if (DBHelpers.Upadate(sql))
{
MessageBox.Show("数据库恢复成功");
}
else
{
MessageBox.Show("数据库恢复失败");
}
}

}


  public class DBHelpers
    {

private static SqlConnection con;

public static SqlConnection Con
{
get
{

if (con == null)
{

con = new SqlConnection(ConfigurationManager.ConnectionStrings["QMXContext"].ConnectionString);
con.Open();
}
else if (con.State == ConnectionState.Broken)
{
con.Close();
con.Open();
}
else if (con.State == ConnectionState.Closed)
{
con.Open();
}



return con;
}

}
public static SqlCommand Cmd
{
get
{
return Con.CreateCommand();
}

}
public static bool Upadate(string sql)
{
SqlCommand cmd = Cmd;
cmd.CommandText = sql;
if (cmd.ExecuteNonQuery()==-1)
{
return true;
}
else
{
return false;
}

}
public static object SelectFromscaler(string sql)
{
SqlCommand cmd = Cmd;
cmd.CommandText = sql;
return cmd.ExecuteScalar();

}

}



 

 

转载于:https://www.cnblogs.com/xiaohaoblog/archive/2012/03/07/2384476.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值