Winform的代码,最好是在数据所在电脑上运行代码,不然会因为权限问题导致失败。
数据库备份:
SqlConnection con = new SqlConnection("Data Source=.;;Initial Catalog=DB_Test;User ID=sa;Password=sa"); string sql = "backup database DB_Test to disk= 'c:\aVb.bak'"; con.Open(); if (!File.Exists("c:\aa.bak")) { SqlCommand com = new SqlCommand(sql, con); com.ExecuteNonQuery(); //执行sql语句 lblmessage.Text = "系统信息:备份成功!"; } else { lblmessage.Text = "系统信息:文件已存在!"; }
数据库还原:
//引用SQLDMO.dll,SQLDMO由Microsoft SQL Server自带的SQLDMO.dll提供,SQLDMO.dll是一个COM对象 SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass(); try { svr.Connect("192.168.89.20", "sa", "Aa123456"); //取得所有的进程列表 SQLDMO.QueryResults qr = svr.EnumProcesses(-1); int iColPIDNum = -1; int iColDbName = -1; //找到和要恢复数据库相关的进程 for (int i = 1; i <= qr.Columns; i++) { string strName = qr.get_ColumnName(i); if (strName.ToUpper().Trim() == "SPID") { iColPIDNum = i; } else if (strName.ToUpper().Trim() == "DBNAME") { iColDbName = i; } if (iColPIDNum != -1 && iColDbName != -1) break; } //将相关进程杀死 for (int i = 1; i <= qr.Rows; i++) { int lPID = qr.GetColumnLong(i, iColPIDNum); string strDBName = qr.GetColumnString(i, iColDbName); if (strDBName.ToUpper() == strDbName.ToUpper()) svr.KillProcess(lPID); } SQLDMO.Restore res = new SQLDMO.RestoreClass(); res.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database; res.Files = strFileName; res.Database = strDbName; res.FileNumber = 1; res.ReplaceDatabase = true; res.SQLRestore(svr); return true; } catch (Exception err) { //throw (new Exception("" + err.Message)); MessageBox.Show("恢复数据库失败,请关闭所有和该数据库连接的程序!" + err.Message); return false; } finally { svr.DisConnect(); }