SqlCommand MyCommand = new SqlCommand(MySQL, conn);
                    try
                    {
                        MyCommand.Connection.Open();
                        MyCommand.ExecuteNonQuery();                       // MessageBox.Show("成功创建数据库", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);                    }
                    catch (Exception ex)
                    {
                        conn.Close();
                        throw ex;
                     
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open)
                            conn.Close();
                    }                    try
                    {
                        SqlCommand MyCommand2 = new SqlCommand(MySQL2, conn);
                        MyCommand2.Connection.Open();
                        MyCommand2.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        conn.Close();
                        throw ex; //此处出错,提示因为数据库正在使用,所以未能获得对数据库的排它访问权。
RESTORE DATABASE 操作异常终止。

                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open)
                            conn.Close();                    }

解决方案 »

  1.   

    你的MySQL变量中的值有毛病,跟代码没有关系。
      

  2.   

      SqlConnection Sql = new SqlConnection(ConnStr);
                SqlCommand cmd = new SqlCommand("RestoreDb", Sql);
                string Str = "exec  RestoreDb  @bkfile='" + strPath + "',@dbname='Project'";
                Sql.Open();
                Sql.ChangeDatabase("master");
                cmd.Connection = Sql;
                cmd.CommandType = CommandType.Text;
                cmd.CommandTimeout = 600;
                cmd.CommandText = Str;
                cmd.ExecuteNonQuery();
                Sql.ChangeDatabase("ZY_Project");
                cmd.Dispose();
               Sql.Close();
               
      

  3.   

    自己搞清楚“什么时候执行这个t-sql功能”的?考虑为什么执行此类及其特殊指令时,此时为什么还有多用户访问?这基本上只能用于初始化应用程序时。如果是运行了一段时间的应用程序,就算你关闭了所有逻辑连接,也有一些物理连接正在连接池里跟数据库连接着。