C # Backup and restore of SQL Server databases

Source: Internet
Author: User

To back up the database:

String connectionString = "server= server name; database= database name; uid= login name; pwd= login Password"; Login name and password to find in SQL Server
private void Btnbackdatabase_click (object sender, EventArgs e)
{
Try
{
SaveFileDialog SF = new SaveFileDialog ();
DialogResult dr = sf. ShowDialog ();
if (dr = = DialogResult.OK)
{
String path = SF. FileName;
String sql = "BACKUP database name to DISK = '" + Path + "'";
SqlConnection con = new SqlConnection (connectionString);
Con. Open ();
SqlCommand cmd = new SqlCommand (sql, con);
Cmd. ExecuteNonQuery ();
MessageBox.Show ("Database backup succeeded");
Con. Close ();
}
}
catch (Exception ex)
{
MessageBox.Show (ex. Message.tostring ());
}
}

Database restore:

private void Btnrestore_click (object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog ();
DialogResult dr = Ofd. ShowDialog ();
if (dr = = DialogResult.OK)
{
Try
{
String cmdtext = @ "Restore Databa SE database name from disk= ' "+ ofd. FileName + "'";
SqlConnection con = new SqlConnection (connectionString);
Con. Open ();
String setoffline = "Alter database name  set Offline with rollback immediate";
String setonline = "Alter database name  set Online with Rollback immediate";
String sql = setoffline + cmdtext + setonline;
SqlCommand cmd = new SqlCommand (sql, con);
Cmd. ExecuteNonQuery ();
Con. Close ();
}
catch (Exception ex)
{
MessageBox.Show (ex). Message);
}
}
}

C # Backup and restore of SQL Server databases

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.