• C#对SQL Server数据库的备份与还原


      备份数据库:

        string connectionString = "server=服务器名称;database=数据库名;uid=登入名;pwd=登入密码";         //登入名和密码在SQL Server中查找
        private void btnBackDataBase_Click(object sender, EventArgs e)
        {
          try
          {
            SaveFileDialog sf = new SaveFileDialog();
            DialogResult dr = sf.ShowDialog();
            if (dr == DialogResult.OK)
            {
              string path = sf.FileName;
              string sql = " BACKUP DATABASE 数据库名 to DISK = '" + path + "'";
              SqlConnection con = new SqlConnection(connectionString);
              con.Open();
              SqlCommand cmd = new SqlCommand(sql, con);
              cmd.ExecuteNonQuery();
              MessageBox.Show("数据库备份成功");
              con.Close();
            }
          }
          catch (Exception ex)
          {
            MessageBox.Show(ex.Message.ToString());
          } 
        }

      数据库还原:

        private void btnRestore_Click(object sender, EventArgs e)
        {
          OpenFileDialog ofd = new OpenFileDialog();
          DialogResult dr = ofd.ShowDialog();
          if (dr == DialogResult.OK)
          {
            try
            {
              string cmdText = @"restore database 数据库名 from disk='" + ofd.FileName + "'";
              SqlConnection con = new SqlConnection(connectionString);
              con.Open();
              string setOffline = "Alter database 数据库名 Set Offline With rollback immediate ";
              string setOnline = " Alter database 数据库名 Set Online With Rollback immediate";
              string sql = setOffline + cmdText + setOnline;
              SqlCommand cmd = new SqlCommand(sql, con);
              cmd.ExecuteNonQuery();
              con.Close();
            }
            catch (Exception ex)
            {
              MessageBox.Show(ex.Message);
            }
          }
        }

  • 相关阅读:
    Microsoft training Kits
    WCF Load Test
    SQL Server Central Management System
    连贯NHibernate 1.0正式发布
    C#全角和半角转换
    Silverlight 2应用所采用的WCF技术
    实用工具特别推荐 Robocopy GUI
    SmtpClient发送邮件遭遇The specified string is not in the form required for a subject.
    SQL Server 2008使用扩展事件进行高级故障排除
    Visual Studio 2010新特性
  • 原文地址:https://www.cnblogs.com/zhanglei93/p/4759185.html
Copyright © 2020-2023  润新知