Sql 数据备份及恢复
private void tlstripBackbase_Click(object sender, EventArgs e) { string strFilePath = string.Empty; string strCmdText = string.Empty; //OpenFileDialog fileDialog = new OpenFileDialog(); FolderBrowserDialog folderBrowser = new FolderBrowserDialog(); if (folderBrowser.ShowDialog() == DialogResult.OK) { // fileDialog.Filter = "备份文件(*.bak)|*.bak|所有文件(*.*)|*.*"; strFilePath = folderBrowser.SelectedPath+ "\\Coffee Shop.bak"; strCmdText= string.Format("backup database [Coffee Shop] to disk ='{0}'WITH INIT", strFilePath); } try { SqlCommand command = new SqlCommand(strCmdText, sqlHelper.getConnection()); command.ExecuteNonQuery(); MessageBox.Show("备份成功!"); sqlHelper.closeConn(); } catch (Exception ex) { MessageBox.Show(ex.Message); sqlHelper.closeConn(); return; } } private void tlstripRestorebase_Click(object sender, EventArgs e) { string strCmdText = string.Empty; string strFilePath = string.Empty; string strCon = "server=.;database=model;uid=sa;pwd=test"; OpenFileDialog fileDialog = new OpenFileDialog(); if (fileDialog.ShowDialog() == DialogResult.OK) { fileDialog.Filter = "备份文件(*.bak)|*.bak|所有文件(*.*)|*.*"; strFilePath = fileDialog.FileName; strCmdText = string.Format("Alter database [Coffee Shop] Set Offline With rollback immediate use master RESTORE DATABASE [Coffee Shop] FROM DISK = '{0}' WITH REPLACE " + " Alter database [Coffee Shop] Set Online With Rollback immediate", strFilePath); } using (SqlConnection connection = new SqlConnection(strCon)) { connection.Open(); try { SqlCommand command = new SqlCommand(strCmdText, connection); command.ExecuteNonQuery(); MessageBox.Show("数据还原成功"); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } }
1.通过执行Sql语句来实现
注意,用Sql语句实现备份与还原操作时,最好不要使用需要备份或还原的数据库连接,而使用master,否则可能会出现如下三个问题:(1)超时时间已到。在操作完成之前超时时间已过或服务器未响应。(2) 在向服务器发送请求时发生传输级错误。(provider:共享内存提供程序,error:0-系统无法打开文件。) (3)从服务器接收结果时发生传输级错误。(provider:共享内存提供程序,error:0 - 系统无法打开文件。) ,如果一定要用这个连接的话,要注意在执行Sql语句前加个Sql语句:use master,这样可能会解决以上问题。
2、还原或删除sql server数据库时,经常会出现:“因为数据库正在使用,所以无法获得对数据库的独占访问权”,解决方法是在还原语句前执行"Alter database BookShop Set Offline With rollback immediate”,还原语句后执行“Alter database BookShop Set Online With Rollback immediate”。