C#中还原数据库中的问题

Mas*_*ian 2 c# sql database sql-server database-restore

我已经定义了所有的东西,而且这段代码是我代码的一部分

if (Sql_Conn == null)
    Sql_Conn = new SqlConnection(Str_Con);
// str_con is my connection string

if (Sql_Conn.State != ConnectionState.Open)
   Sql_Conn.Open();

Data_Table = new DataTable();
DataA_dapter = new SqlDataAdapter();

Sql_Cmd = new SqlCommand();
Sql_Cmd.Connection = Sql_Conn; // 

string sql = "RESTORE DATABASE  [" + str_directory + "] From DISK = " +
                        "'" + strFileName + "' ; ";
// str_directory is the source of my database as DB.MDF
// srtFileName is the directory of DB.bak
Sql_Cmd.CommandType = CommandType.Text;
Sql_Cmd.CommandText = sql;

try
{
    Sql_Cmd.ExecuteNonQuery();
}
catch (SqlException Error_Exception)
{
   MessageBox.Show("Error");
}
Run Code Online (Sandbox Code Playgroud)

当我string sql在SQL Sserver中使用新查询时,我没有问题,我的数据库恢复成功,但当我使用此代码与c#时,我看到此错误

错误:{System.Data.SqlClient.SqlException:RESTORE无法处理数据库'E:/DB.mdf',因为此会话正在使用它.建议在执行此操作时使用master数据库.RESTORE DATABASE异常终止.

我想恢复我的数据库.我必须在我的第一个代码中打开连接,当我想恢复我的数据库时,我看到了Exception.

现在我该如何恢复我的数据库?请帮我.

Guf*_*ffa 5

您无法还原已连接的确切数据库.正如错误消息所提到的,您应该使用master数据库.

在你的连接字符串中使用database=master.