数据库备份
private void btnBackUp_Click(object sender, EventArgs e) { if (this.txtDBPath.Text.Trim().Length == 0) { Msg.MsgBox("地址不能为空!"); return; } string _StringDB = ConfigurationManager.ConnectionStrings["db"].ConnectionString.ToString(); String[] strs = _StringDB.Split(';'); int _serverName0 = strs[0].IndexOf("="); string _serverName1 = strs[0].Substring(_serverName0 + 1); int _dbName0 = strs[1].IndexOf("="); string _dbName1 = strs[1].Substring(_dbName0 + 1); int _dbUser0 = strs[2].IndexOf("="); string _dbUser1 = strs[2].Substring(_dbUser0 + 1); int _dbPwd0 = strs[3].IndexOf("="); string _dbPwd1 = strs[3].Substring(_dbPwd0 + 1); string ServerName =_serverName1; string DbName = _dbName1; string DbUser =_dbUser1; string DbPwd = _dbPwd1; string SaveFilePath = System.Configuration.ConfigurationManager.AppSettings["Path"]; int s =SaveFilePath.LastIndexOf (@"."); string add=DateTime .Now .ToString ("yyyyMMddHHmmss"); SaveFilePath = SaveFilePath.Insert(s, add); DbBackup(ServerName, DbName, DbUser, DbPwd, SaveFilePath); } public static void DbBackup(string ServerName,string DbName,string DbUser,string DbPwd,string SaveFilePath) { SQLDMO.Backup oBackup = new SQLDMO.BackupClass(); SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass(); try { oSQLServer.LoginSecure = false; oSQLServer.Connect(ServerName, DbUser, DbPwd);//服务器名、账号、密码 oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database; oBackup.Database = DbName; oBackup.Files = SaveFilePath; oBackup.BackupSetName = DbName; oBackup.BackupSetDescription = "数据库备份"; oBackup.Initialize = true; oBackup.SQLBackup(oSQLServer); } catch { Msg.MsgBox("数据库备份失败!"); throw; } finally { oSQLServer.DisConnect(); Msg.MsgBox(SaveFilePath+"数据库备份成功!"); } }
君子性非异也,善假于物也!