C#代码备份还原MSSQL数据库

备份数据库

///

/// 备份配置文件config.xml中数据库 /// /// 备份文件路径 /// public static bool DataBackupConfigDB(string backupFolder) { //获取配置文件中sql数据库名 string dbName = "SqlDB"; string name = dbName + DateTime.Now.ToString("yyyyMMddHHmmss"); string procname; string sql; //创建连接对象 SqlConnection conn = new SqlConnection(GetConnStr()); conn.Open(); //打开数据库连接 //删除逻辑备份设备,但不会删掉备份的数据库文件 procname = "sp_dropdevice"; SqlCommand sqlcmd1 = new SqlCommand(procname, conn); sqlcmd1.CommandType = CommandType.StoredProcedure; SqlParameter sqlpar = new SqlParameter(); sqlpar = sqlcmd1.Parameters.Add("@logicalname", SqlDbType.VarChar, 20); sqlpar.Direction = ParameterDirection.Input; sqlpar.Value = dbName; try //如果逻辑设备不存在,略去错误 { sqlcmd1.ExecuteNonQuery(); } catch { MessageBox.Show("错误的备份文件目录"); } //创建逻辑备份设备 procname = "sp_addumpdevice"; SqlCommand sqlcmd2 = new SqlCommand(procname, conn); sqlcmd2.CommandType = CommandType.StoredProcedure; sqlpar = sqlcmd2.Parameters.Add("@devtype", SqlDbType.VarChar, 20); sqlpar.Direction = ParameterDirection.Input; sqlpar.Value = "disk"; sqlpar = sqlcmd2.Parameters.Add("@logicalname", SqlDbType.VarChar, 20);//逻辑设备名 sqlpar.Direction = ParameterDirection.Input; sqlpar.Value = dbName; sqlpar = sqlcmd2.Parameters.Add("@physicalname", SqlDbType.NVarChar, 260);//物理设备名 sqlpar.Direction = ParameterDirection.Input; sqlpar.Value = backupFolder + name + ".bak"; try { int i = sqlcmd2.ExecuteNonQuery(); } catch (Exception err) { string str = err.Message; } //备份数据库到指定的数据库文件(完全备份) sql = "BACKUP DATABASE " + dbName + " TO " + dbName + " WITH INIT"; SqlCommand sqlcmd3 = new SqlCommand(sql, conn); sqlcmd3.CommandType = CommandType.Text; try { sqlcmd3.ExecuteNonQuery(); } catch (Exception err) { string str = err.Message; conn.Close(); return false; } conn.Close();//关闭数据库连接 return true; }  

 

还原数据库时如果使用

 

 

RESTORE DATABASE dbName(数据库名) from DISK = 'e:/' to replace

 

 

sql错误提示:RESTORE 无法处理数据库dbName 因为它正由此会话使用 建议在执行此操作时使用 master 数据库

 

在网上终于找到了解决方法,具体代码如下:

///

/// 还原数据库文件 /// /// 数据库备份文件(含路径) /// public static bool DataRestoreConfigDB(string dbFile) { //sql数据库名 string dbName = "SqlDB"; //创建连接对象 SqlConnection conn = new SqlConnection(GetConnStr()); //还原指定的数据库文件 string sql =string.Format("use master ;declare @s varchar(8000);select @s=isnull(@s,'')+' kill '+rtrim(spID) from master..sysprocesses where dbid=db_id('{0}');select @s;exec(@s) ;RESTORE DATABASE {1} FROM DISK = N'{2}' with replace",dbName,dbName,dbFile); SqlCommand sqlcmd = new SqlCommand(sql, conn); sqlcmd.CommandType = CommandType.Text; conn.Open(); try { sqlcmd.ExecuteNonQuery(); } catch (Exception err) { string str = err.Message; conn.Close(); return false; } conn.Close();//关闭数据库连接 return true; } 

你可能感兴趣的:(C#,VS2010)