简体   繁体   中英

Restoring SQL Server 2005 database using C#. Rollback issue

Hi I'm just starting to learn C#. I am trying to restore a .bak file. However I am getting the error. Exclusive access cannot be obtained because the database is in use.

I did my research here and here both says I have to perform a rollback. I do not know how to apply rollback in my restore code.

    public void RestoreDatabase(String RestorePath)
    {
        try
        {
            SqlConnection sqlCon = new SqlConnection("Data Source=RITZEL-PC\\SQLEXPRESS;User ID=NNIT-Admin;Password=password;Initial Catalog=master;");
            ServerConnection connection = new ServerConnection(sqlCon);
            Server sqlServer = new Server(connection);

            Restore restoreDB = new Restore();

            restoreDB.Database = "NNIT DB";
            restoreDB.Action = RestoreActionType.Database;
            restoreDB.Devices.AddDevice(RestorePath, DeviceType.File);

            restoreDB.ReplaceDatabase = true; // will overwrite any existing DB     
            restoreDB.NoRecovery = false; // NoRecovery = true;

            restoreDB.SqlRestore(sqlServer);

            MessageBox.Show("Restored");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + " " + ex.InnerException);
        }
    }

Using SMO you can set user access and rollback like this:

Server sqlServer = new Server(connection);

Database db = sqlServer.Databases["DbToRestore"];

if (db != null)
{
    sqlServer.KillAllProcesses(db.Name);
    db.DatabaseOptions.UserAccess = DatabaseUserAccess.Multiple;
    db.Alter(TerminationClause.RollbackTransactionsImmediately);
}

Restore restoreDB = new Restore();

Does this work?

SqlCommand cmd = new SqlCommand("ALTER DATABASE yourdatabasename SET MULTI_USER WITH ROLLBACK IMMEDIATE", sqlConn);
cmd.ExecuteNonQuery();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM