-
:方法一(不使用SQLDMO):
-
?
-
///
-
///备份方法
-
///
-
SqlConnectionconn=newSqlConnection("Server=.;Database=master;UserID=sa;Password=sa;");
-
?
-
SqlCommandcmdBK=newSqlCommand();
-
cmdBK.CommandType=CommandType.Text;
-
cmdBK.Connection=conn;
-
cmdBK.CommandText=@"backupdatabasetesttodisk='C:/ba'withinit";
-
?
-
try
-
{
-
conn.Open();
-
cmdBK.ExecuteNonQuery();
-
MessageBox.Show("Backupsuccessed.");
-
}
-
catch(Exceptionex)
-
{
-
MessageBox.Show(ex.Message);
-
}
-
finally
-
{
-
conn.Close();
-
conn.Dispose();
-
}
-
?
-
?
-
///
-
///还原方法
-
///
-
SqlConnectionconn=newSqlConnection("Server=.;Database=master;UserID=sa;Password=sa;Trusted_Connection=False");
-
conn.Open();
-
?
-
//KILLDataBaseProcess
-
SqlCommandcmd=newSqlCommand("SELECTspidFROMsysprocesses,sysdatabasesWHEREsysprocesses.dbid=sysdatabases.dbidANDsysdatabases.Name='test'",conn);
-
SqlDataReaderdr;
-
dr=cmd.ExecuteReader();
-
ArrayListlist=newArrayList();
-
while(dr.Read())
-
{
-
list.Add(dr.GetInt16(0));
-
}
-
dr.Close();
-
for(inti=0;i<list.Count;i++)
-
{
-
cmd=newSqlCommand(string.Format("KILL{0}",list),conn);
-
cmd.ExecuteNonQuery();
-
}
-
?
-
SqlCommandcmdRT=newSqlCommand();
-
cmdRT.CommandType=CommandType.Text;
-
cmdRT.Connection=conn;
-
cmdRT.CommandText=@"restoredatabasetestfromdisk='C:/ba'";
-
?
-
try
-
{
-
cmdRT.ExecuteNonQuery();
-
MessageBox.Show("Restoresuccessed.");
-
}
-
catch(Exceptionex)
-
{
-
MessageBox.Show(ex.Message);
-
}
-
finally
-
{
-
conn.Close();
-
}
?
?
-
方法二(使用SQLDMO):
-
?
-
///
-
///备份方法
-
///
-
SQLDMO.Backupbackup=newSQLDMO.BackupClass();
-
SQLDMO.SQLServerserver=newSQLDMO.SQLServerClass();
-
//显示进度条
-
SQLDMO.BackupSink_PercentCompleteEventHandlerprogress=newSQLDMO.BackupSink_PercentCompleteEventHandler(Step);
-
backup.PercentComplete+=progress;
-
?
-
try
-
{
-
server.LoginSecure=false;
-
server.Connect(".","sa","sa");
-
backup.Action=SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
-
backup.Database="test";
-
backup.Files=@"D:/test/myProg/backupTest";
-
backup.BackupSetName="test";
-
backup.BackupSetDescription="Backupthedatabaseoftest";
-
backup.Initialize=true;
-
backup.SQLBackup(server);
-
MessageBox.Show("Backupsuccessed.");
-
}
-
catch(Exceptionex)
<