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!";
}
新闻热点
疑难解答