首页 > 开发 > 综合 > 正文

C#还原数据库

2024-07-21 02:26:12
字体:
来源:转载
供稿:网友

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!";


  }

注册会员,创建你的web开发资料库,
上一篇:在C#中使用Ping

下一篇:C#调用输入法

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表