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();

}

}



 

 

posted @ 2012-03-07 23:46  腰里揣着一块砖  阅读(1170)  评论(3编辑  收藏  举报