简体   繁体   中英

BackUp and Restore Sql Database By Admin User in Asp.Net, C#

Here, I have show my c# code for BackUp and Restore with Sql Database

In that back up is working properly but when i try to restore the database from backup folder, that time one error is occurred, and the error is:

RESTORE cannot process database 'UsersDB' because it is in use by this session. It is recommended that the master database be used when performing this operation. RESTORE DATABASE is terminating abnormally.

BackUp button:

protected void btnbackup_Click(object sender, EventArgs e)
    {
        sqlcon.ConnectionString = (System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ToString());
        string destdir = "C:\\backupdb";
        if (!System.IO.Directory.Exists(destdir))
        {
            System.IO.Directory.CreateDirectory("C:\\backupdb");
        }
        try
        {
            sqlcon.Open();
            sqlcmd = new SqlCommand("backup database UsersDB to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
            sqlcmd.ExecuteNonQuery();
            Response.Write("Backup database successfully");
        }
        catch (Exception ex)
        {
            Response.Write("Error During backup database!");
        }
    }

Restore Button:

 protected void btnrestore_Click(object sender, EventArgs e)
    {
        try
        {


        sqlcon.ConnectionString = (System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ToString());
        sqlcon.Open();
        string destdir = "C:\\backupdb\\11082014_121403.Bak";

        sqlcmd = new SqlCommand("Restore database UsersDB from disk='C:11082014_143650.Bak' ", sqlcon);
        sqlcmd.ExecuteNonQuery();
        Response.Write("restore database successfully");
        }
        catch (Exception ex)
        {
            Response.Write("Error During backup database!");
        }

    }

Thanks in advance

In the connection string you have connected to the database you want to backup.

Instead, connect to a different database or no database at all and it will work.

The error message itself saying that you can't connect to the exact database that you connected to.

You need to change your connection string so that instead of,

initial catalog=test_db 

use this,

initial_catalog=master. 

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