SQL SERVER数据库备份和恢复函数

来源:互联网 发布:阿里云app 什么区别 编辑:程序博客网 时间:2024/05/21 17:23

public bool DataBackup(string path)
    {
        if(File.Exists(path+"BottleDetectionLine.bak"))
            File.Delete(path+"BottleDetectionLine.bak");
        string sql = "backup database xx to disk = '" + path + "xx.bak'";       重要的是sqi语句
        try
        {
            helper.ExecuteCommand(sql);
            return true;
        }
        catch { }
        finally
        {

            helper.ConClose();
        }
       
        return false;
    }
    public bool DataRestore(string path)
    {
        SqlConnection con = new SqlConnection(@"Data Source=LONG-PC\SQL2000;Initial Catalog=Master;Integrated Security=True"); 这里使用与目标数据库不同的数据库
        con.Open();
        string sql = "ALTER DATABASE xx SET OFFLINE WITH ROLLBACK IMMEDIATE;" + "RESTORE DATABASE xx FROM DISK = '" + path + "';" +
            "ALTER DATABASE xx SET ONLINE WITH ROLLBACK IMMEDIATE;";          先断开所有连接,恢复,打开
        SqlCommand com=new SqlCommand(sql,con);

        try
        {
            com.ExecuteNonQuery();
            return true;
        }
        catch
        { }
        finally
        {
            con.Close();
        }
       
        return false;
    }