First add a reference of Microsoft SQLDMO Object Library from COM tab .Then Write the below code
//Function for Restore
private void Restore()
{
try
{
this.Cursor = Cursors.WaitCursor;
//create an instance of a server class
SQLDMO._SQLServer srv = new SQLDMO.SQLServerClass();
//connect to the server
srv.Connect("(local)","sa",""); //srv.Connect(servername,userid,password)
//create a restore class instance
SQLDMO.Restore res = new SQLDMO.RestoreClass();
//set the backup device = files property ( easy way )
res.Devices = res.Files;
//set the files property to the File Name text box
res.Files =textBox1.Text;//give full path with restore filename
//set the database to the chosen database
res.Database = "databaseName";
// Restore the database
res.ReplaceDatabase = true;
res.SQLRestore(srv);
MessageBox.Show("Database restored successfully.", "Restore Successfull");
this.Cursor = Cursors.Default;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error");
}
}
//Function for Backup
private void BackUp()
{
try
{
Class1.con.Close();
this.Cursor = Cursors.WaitCursor;
//create an instance of a server class
SQLDMO._SQLServer srv = new SQLDMO.SQLServerClass();
//connect to the server
srv.Connect("(local)","sa",""); //srv.Connect(servername,userid,password)
//create a backup class instance
SQLDMO.Backup bak = new SQLDMO.BackupClass();
//set the backup device = files property ( easy way )
bak.Devices = bak.Files;
//set the files property to the File Name text box
//
bak.Files = this.textBox1.Text;//give full path with bakup filename
//set the database to the chosen database
bak.Database = "databasename";
//perform the backup
bak.SQLBackup(srv);
MessageBox.Show("Database successfully backed up.", "Backup Successfull");
this.Cursor = Cursors.Default;
}
catch(Exception err)
{
this.Cursor = Cursors.Default;
MessageBox.Show(err.Message,"Error");
}
}
No comments:
Post a Comment