天天@BLOG

脖子越来越疼,脑袋越来越钝
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#还原数据库

Posted on 2006-08-07 16:37  天天在线  阅读(2608)  评论(1编辑  收藏  举报

public static string RestoreDatabase(string backfile)
  {
   ///杀死原来所有的数据库连接进程
   ///

   SqlConnection conn=new SqlConnection ();
   conn.ConnectionString ="Data Source=.;Initial Catalog=master;User ID=sa;pwd =teny123";
   conn.Open ();
   
   string sql="SELECT spid FROM sysprocesses ,sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name='pubs'";

   SqlCommand cmd1 = new SqlCommand(sql, conn);
   SqlDataReader dr;

   ArrayList list = new ArrayList();

   try
   {
    dr = cmd1.ExecuteReader();
   

    
    while(dr.Read())
    {
     list.Add(dr.GetInt16(0));
    }
    dr.Close();

   }
   catch(SqlException eee)
   {
    MessageBox.Show (eee.ToString ());
   }
   finally
   {
    conn.Close ();
                  
   }

   MessageBox.Show (list.Count .ToString ());


   for(int i = 0; i < list.Count; i++)
   {
    cmd1 = new SqlCommand(string.Format("KILL {0}", list[i].ToString ()), conn);
    cmd1.ExecuteNonQuery();

    MessageBox.Show ("you have killed thread "+list[i].ToString ());

   }

   //这里一定要是master数据库,而不能是要还原的数据库,因为这样便变成了有其它进程
   //占用了数据库。


   string constr = @"Data Source=.;Initial Catalog=master;User ID=sa;pwd =teny123 ";
   string database = "pubs";
   string path = @"d:\1.mdf";
   //string BACKUP = String.Format("backup database {0} to disk='{1}'", database, path);
   string BACKUP = String.Format("RESTORE DATABASE {0}  FROM DISK = '{1}'", database, path);

   SqlConnection con = new SqlConnection(constr);
   SqlCommand cmd = new SqlCommand(BACKUP, con);
   con.Open();
   try
   {
    cmd.ExecuteNonQuery();
    MessageBox.Show("还原成功");
   }
   catch(SqlException ee)
   {
    //throw(ee);

    //MessageBox.Show("还原失败");

    MessageBox.Show (ee.ToString ());

   }
   finally
   {
    con.Close();
   }


                    return "成功与否字符串";

  //return "restore successfully!";


  }

@忙碌,不代表有效率;方法,远胜于苦干