backup
string connectionString1 = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database1.mdf;Database=Database1;Integrated Security=True; User Instance=True");
SqlConnection cn = new SqlConnection(connectionString1);
cn.Open();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = @"BACKUP DATABASE Database1 TO DISK = 'C:\SRI2Works.bak'";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
reader = cmd.ExecuteReader();
cn.Close();
MessageBox.Show("Database Backup Successfull.");
restore
string connectionString1 = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database1.mdf;Database=Database1;Integrated Security=True; User Instance=True");
SqlConnection cn = new SqlConnection(connectionString1);
cn.Open();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = @"use master; RESTORE DATABASE Database1 FROM DISK = 'C:\SRI2Works.bak'";
cmd.CommandText = "DBCC CHECKDB ('Database1')";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
reader = cmd.ExecuteReader();
cn.Close();
MessageBox.Show("Database Restored Successfull.");
This code runs successfully but doesn't make any changes.
Try this code in Restore database:
private void restoreButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
string sqlStmt2 = string.Format("ALTER DATABASE [" + database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE DATABASE [" + database + "] FROM DISK='" + textBox2.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER DATABASE [" + database + "] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
bu4.ExecuteNonQuery();
MessageBox.Show("database restoration done successefully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
For more explanation check out this tutorial: Backup & Restore Sql Server database using C#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With