我先为了实例写了一个demo:
在窗体中分别拖了两个按钮,button1 和button2,还原数据库,后者是打开该数据库再关闭。代码如下:
private void button1_Click(object sender, EventArgs e)
        {            
            SQLDMO.Restore oRestore = new SQLDMO.RestoreClass();
            SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
            try
            {
                oSQLServer.LoginSecure = false;
                oSQLServer.Connect("localhost", "sa", "34373");
                oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
                oRestore.Database = "es_CostumeStore_01_01tst";
                oRestore.Files = System.IO.Path.Combine(Application.StartupPath, "IniData");
                oRestore.FileNumber = 1;
                oRestore.ReplaceDatabase = true;                
                oRestore.SQLRestore(oSQLServer);
                MessageBox.Show("数据初始化成功!");
            }
            catch
            {
                MessageBox.Show("数据初始化失败!");
            }
            finally
            {
                oSQLServer.DisConnect();
            }
        }        private void button2_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "server=localhost;database=es_CostumeStore_01_01tst;uid=sa;pwd=34373";
            con.Open();
            con.Close();
            con.Dispose();
            con = null;        }
如果单独执行button1能还原成功,但如果先执行button2再执行button1就会报错,错误原因:因为数据库正在使用,所以未能获得对数据库的排它访问权。  但是我在button2中打开了数据库又关闭了,为什么还要报错呢,有没其它办法解决,因为我要先去读数库中的数据后根据其值去决定要不要还原,谢谢大家帮忙。。

解决方案 »

  1.   

    先执行下这个..然后再去还原数据库..create   table   table_sp_who(spid   int,   ecid   int,   status   varchar(100),   loginame   varchar(100),   
        hostname   varchar(100),   blk   int,   dbname   varchar(100),   cmd   varchar(100))   
      insert   table_sp_who   exec   sp_who   
      declare   @dbname   varchar(100)   
      declare   @spid   int   
      --数据库名字   
      set   @dbname='pubs'   
      --kill正在使用该数据库的进程   
      DECLARE   spid_db   CURSOR   
            FOR   SELECT   spid   FROM   table_sp_who   where   dbname=@dbname   
      OPEN   spid_db   
      FETCH   NEXT   FROM   spid_db   into   @spid   
        
      WHILE   @@FETCH_STATUS   =   0   
      BEGIN   
                  print   '杀死正在使用数据库'+@dbname+'的进程:'+convert(varchar(10),   @spid)+'\n'   
                  exec('kill   '+@spid)   
                  FETCH   NEXT   FROM   spid_db   INTO   @spid         
      END   
        
      CLOSE   spid_db   
      DEALLOCATE   spid_db   
      --清除数据   
      drop   table   table_sp_who