user2252491
user2252491

Reputation: 61

SQL Server backup&restore

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.

Upvotes: 6

Views: 15025

Answers (4)

user4340666
user4340666

Reputation: 1473

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#

Upvotes: 7

Mansoor
Mansoor

Reputation: 133

RESTORE DATABASE [C] FROM DISK = 'D:\\Inventory.bak' WITH RECOVERY, 
MOVE 'Inventory_Data'
 TO 'C:\\Program Files\\Microsoft SQL Server\\MSSQL\\Data\\c_Data.MDF', 
MOVE 'Inventory_Log' 
TO 
'C:\\Program Files\\Microsoft SQL Server\\MSSQL\\Data\\c_Log.LDF', 
REPLACE, stats =1

The only thing you have to care about, restore database is not created in MS SQL SERVER. In my case after query run it should create a new database with the name [C] and create its file at path of [C:\\Program Files\\Microsoft SQL Server\\MSSQL\\Data\\]

Upvotes: 0

Lallawmkima
Lallawmkima

Reputation: 1

Remove the following statement from your code:

cmd.CommandText = "DBCC CHECKDB ('Database1')";

And If you want to overwrite the existing database use the following command for commandtext:

cmd.CommandText = @"use master; RESTORE DATABASE Database1 FROM DISK = 'C:\SRI2Works.bak' WITH REPLACE";

Upvotes: 0

Obama
Obama

Reputation: 2612

for example we have 2 Menu Strip; one for back up and the other for the restore so they execute their methods! Try this :

    private void saveDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            BackupDatabase();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + " \nPlease choose the folder Sauvegardes to backup !");
        }

    }
    private void restoreDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            RestoreDatabase();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    private void BackupDatabase()
    {
        saveFileDialogBackUp.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + @"Sauvegardes";
        if (saveFileDialogBackUp.ShowDialog() == DialogResult.OK)
        {
            Con.ExecuteCmd("BACKUP DATABASE MyFooDatabase TO DISK = '" + saveFileDialogBackUp.FileName + "'");
            MessageBox.Show("Success , done!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
    private void RestoreDatabase()
    {
        openFileDialogBackUp.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + @"Sauvegardes";
        if (openFileDialogBackUp.ShowDialog() == DialogResult.OK)
        {
            Con.ExecuteCmd(" USE MASTER RESTORE DATABASE MyFooDatabase FROM DISK = '"+openFileDialogBackUp.FileName+"' WITH REPLACE");
            MessageBox.Show("Database Restored", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

    }

Upvotes: 0

Related Questions