使用C#还原SQL数据库

时间:2012-05-17 16:44:01

标签: c# sql database-restore

我正在尝试使用C#代码恢复sql数据库。备份工作正常。但是当恢复数据库时,它会给我一个错误。 我正在使用Microsoft.SqlServer.Management.Smo;进行此操作。 错误是 {“System.Data.SqlClient.SqlError:RESTORE无法处理数据库'TempDb',因为此会话正在使用它。 建议在执行此操作时使用master数据库。“}

在几个帖子中,它说将数据库设置为主数据库。我也试过了。但它给了我同样的错误。 连接字符串:connectionString = @“server =(local); Initial Catalog = Master; Integrated Security = True;”;

我的代码如下:

openFileDialog1.ShowDialog();
        string databaseName = "TempDb";
        Restore sqlRestore = new Restore();

        BackupDeviceItem deviceItem = new BackupDeviceItem(openFileDialog1.FileName, DeviceType.File);
        sqlRestore.Devices.Add(deviceItem);
        sqlRestore.Database = databaseName;

        DataConnection dataConnection = new DataConnection();
        ServerConnection connection = new ServerConnection(dataConnection.DataBaseConnection);
        Server sqlServer = new Server(connection);

        Database db = sqlServer.Databases[databaseName];
        sqlRestore.Action = RestoreActionType.Database;
        String dataFileLocation = db.FileGroups[0].Files[0].FileName;
        String logFileLocation = db.LogFiles[0].FileName;
        db = sqlServer.Databases[databaseName];
        RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);


        sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
        sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName + "_log", logFileLocation));
        sqlRestore.ReplaceDatabase = true;
        sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
        sqlRestore.PercentCompleteNotification = 10;
        sqlRestore.PercentComplete += new PercentCompleteEventHandler(sqlRestore_PercentComplete);
        sqlRestore.SqlRestore(sqlServer);
        db = sqlServer.Databases[databaseName];
        db.SetOnline();
        sqlServer.Refresh();

3 个答案:

答案 0 :(得分:1)

this code For Restore Database,Please Type Code In C#:

SqlConnection ObjConnection=new SqlConnection("Your Connection String");
ObjConnection.Open();
                SqlCommand ObjCommand = new SqlCommand();
                ObjCommand.Connection = ObjConnection;
                ObjCommand.CommandText = "Use Master   ALTER DATABASE YourDatabaseName SET                 OFFLINE WITH ROLLBACK IMMEDIATE  " +
                "Restore Database YourDatabaseName From Disk='" + LblPath.Text + "'" +
                "   ALTER DATABASE YourDatabaseName SET ONLINE WITH ROLLBACK IMMEDIATE";
                ObjCommand.CommandType = CommandType.Text;
                ObjCommand.ExecuteNonQuery();
Help:LblPath.Text is a Label Control Contain Path Backup Database You!
Mojtaba From IRAN

答案 1 :(得分:0)

您的数据库似乎仍在被其他登录使用。尝试在恢复之前将其带到单用户模式,这确实有帮助。确保使用相同的连接对象将数据库转换为单用户模式,然后恢复,然后将其恢复为多用户模式。

你可以试试这个,

SqlConnection connection = new SqlConnection("connection string");
SqlCommand cmd = new SqlCommand("ALTER DATABASE <database name> SET SINGLE_USER WITH ROLLBACK IMMEDIATE", connection);

cmd.Connection.Open();
cmd.ExecuteNonQuery();

return connection; //to use the same connection for restore activity and setting it to multi user mode again


//up on completion of restore activity, take the database to multi user mode.
//ALTER DATABASE <database name> SET MULTI_USER

答案 2 :(得分:0)

此代码用于恢复数据库

var conString = System.Configuration.ConfigurationManager.ConnectionStrings["CONSTRING"];
string strConnString = conString.ConnectionString;
SqlConnection cs = new SqlConnection(strConnString);

        try
        {
            cs.Open();
            String sqlquery = "Use Master ALTER DATABASE databasename SET OFFLINE WITH ROLLBACK IMMEDIATE RESTORE DATABASE databasename FROM DISK ='" + txtRestoreFileLoc.Text + "' ALTER DATABASE databasename SET ONLINE WITH ROLLBACK IMMEDIATE";
            SqlCommand cmd = new SqlCommand(sqlquery, cs);
            cmd.ExecuteNonQuery();
            cs.Close();
            cs.Dispose();
            MessageBox.Show("restore complete");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

        }