当前位置: 移动技术网 > IT编程>开发语言>.net > Ext sqlserver C# 数据库备份还原代码,给大家参考下

Ext sqlserver C# 数据库备份还原代码,给大家参考下

2018年03月23日  | 移动技术网IT编程  | 我要评论
 
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <title>Login11</title>
    <script src="../../ext/ext-all.js" type="text/javascript">
       
    </script>
    <link href="../../ext/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
    <script src="../../ext/locale/ext-lang-zh_CN.js" type="text/javascript">
       
    </script>
    <script type="text/javascript">
        Ext.onReady(function () {
            Ext.tip.QuickTipManager.init();
 
            var myMask = new Ext.LoadMask(Ext.getBody(), {
                id: 'mask',
                msg: "配置操作中,请稍等..."
            });
 
            var mystore = Ext.create('Ext.data.Store', {
                fields: ['Name', 'CreationTime', 'Length', 'FullName'],
                autoLoad: true,
                pageSize: 10,
                proxy: {
                    type: 'ajax',
                    url: '/AdLogin/filedata',
                    reader: {
                        type: 'json',
                        root: 'd'
                    }
                }
            });
            Ext.delfile = function (file) {
                myMask.show();
                Ext.Ajax.request({
                    url: '/AdLogin/deleFile?file=' + file,
                    async: true,
                    success: function (response, opts) {
                        myMask.hide();
                        var obj = Ext.decode(response.responseText);
                        Ext.Msg.alert("提醒", "删除成功");
                        mystore.load();
                    },
                    failure: function (response, opts) {
 
                    }
                });
 
            }
 
            Ext.restore = function (file) {
                myMask.show();
                Ext.Ajax.request({
                    url: '/AdLogin/reStore?file=' + file,
                    async: true,
                    success: function (response, opts) {
                        myMask.hide();
                        var obj = Ext.decode(response.responseText);
                        Ext.Msg.alert("提醒", "还原成功");
 
 
                    },
                    failure: function (response, opts) {
 
                    }
                });
            }
            function bfstore() {
                myMask.show();
                Ext.Ajax.request({
                    url: '/AdLogin/bfStore',
                    async: true,
                    success: function (response, opts) {
                        myMask.hide();
                        Ext.Msg.alert("提醒", "备份成功");
                        mystore.load();
                    },
                    failure: function (response, opts) {
 
                    }
                });
 
            }
 
            var bfButton = Ext.create("Ext.Button", {
                text: '备份数据库',
                handler: function () {
                    bfstore();
                }
            });
 
            var mygrid = Ext.create('Ext.grid.Panel', {
                title: '数据库管理',
                layout: 'fit',
                dockedItems: [{
                    xtype: 'toolbar',
                    dock: 'top',
                    items: [bfButton]
                }],
                store: mystore,
                bbar: Ext.create('Ext.toolbar.Paging', {
                    store: mystore,
                    dock: 'bottom',
                    displayInfo: true
                }),
 
                columns: [{
                    header: '操作',
                    width: 180,
                    dataIndex: 'Name',
                    renderer: function (value) {
                        return ' <a href="#" onclick="Ext.delfile(\'' + value + '\')">删除备份</a>  <a href="#" onclick="Ext.restore(\'' + value + '\')">还原数据库</a>';
                    }
                }, {
                    header: '文件名称',
                    dataIndex: 'Name',
                    width: 200
                },
                {
                    header: '创建日期',
                    dataIndex: 'CreationTime',
                    width: 200,
                    renderer: function (value) {
                        var dt = new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
                        return Ext.Date.format(dt, 'Y-m-d h:m:s');
                    }
                },
                {
                    header: '备份大小',
                    width: 200,
                    dataIndex: 'Length',
                    renderer: function (value) {
                        return (value / 1024/1024).toFixed(2)+"MB";
                    }
                },
                {
                    header: '文件路径',
                    width: 400,
                    dataIndex: 'FullName'
                }]
            });
 
 
            Ext.create('Ext.container.Viewport',
            {
                layout: 'fit',
                items: [mygrid]
            });
 
 
        });
    </script>
</head>
<body>
    <div>
    </div>
</body>
</html>
 
 
 
 
 
 
 
 
  public ActionResult filedata()
        {
            string path = Server.MapPath("/backdata/");
            DirectoryInfo di = new DirectoryInfo(path);
            FileInfo[] list = di.GetFiles();
            List<FileInfo> list1 = new List<FileInfo>();
            for (int i = 0; i < list.Length; i++)
            {
                list1.Add(list[i]);
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);
            int allcount = list1.Count();
            list1 = list1.Select(d => d).OrderByDescending(d => d.CreationTime).Skip(start).Take(limit).ToList();
            return Content("{\"total\": " + allcount + ", d: " + serializer.Serialize(list1.Select(t => new {t.CreationTime,t.Name,t.FullName,t.Length })) + " }");
 
        }
        public ActionResult deleFile()
        {
            string file = Request.QueryString["file"];
            string path = Server.MapPath("/backdata/") + file;
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
            return Content("{success:true}");
        }
        string database = "haoyhb";
        public ActionResult reStore()
        {
            string file = Request.QueryString["file"];
            string path = Server.MapPath("/backdata/") + file;
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);
            DbHelperSQL.RestoreDatabase(fileInfo.FullName, database);
            return Content("{success:true}");
        }
 
        public ActionResult bfStore() {
            DbHelperSQL.BackUpDataBase(Server.MapPath("/backdata/") + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bak", database);
            return Content("{success:true}");
        }
 
 
 
 
   public static bool BackUpDataBase(string databasefile, string database)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                if (File.Exists(databasefile))
                {
                    File.Delete(databasefile);
                }
                //还原的数据库MyDataBase
                string sql = "BACKUP DATABASE " + database + " TO DISK = '" + databasefile + "' ";
                conn.Open();
                SqlCommand comm = new SqlCommand(sql, conn);
                comm.CommandType = CommandType.Text;
                try
                {
                    comm.ExecuteNonQuery();
                }
                catch (Exception err)
                {
                    string str = err.Message;
                    conn.Close();
 
                    return false;
                }
 
                conn.Close();//关闭数据库连接
                return true;
            }
        }
 
 
 
 
        //以下是还原数据库,稍微麻烦些,要关闭所有与当前数据库相连的连接------------------------------------
 
        //--------------------------------------------------------------------------------------------------------------------------
        public static string RestoreDatabase(string backfile, string database)
        {
            ///杀死原来所有的数据库连接进程
 
 
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "Data Source=.;Initial Catalog=master;User ID=sa;pwd =sa";
            conn.Open();
 
            string sql = "SELECT spid FROM sysprocesses ,sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name='" + database + "'";
            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());
                return "还原失败";
            }
            finally
            {
                conn.Close();
            }
            //MessageBox.Show(list.Count.ToString());
            for (int i = 0; i < list.Count; i++)
            {
                conn.Open();
                cmd1 = new SqlCommand(string.Format("KILL {0}", list[i].ToString()), conn);
                cmd1.ExecuteNonQuery();
                conn.Close();
                // MessageBox.Show("系统已经清除的数据库线程: " + list[i].ToString() + "\r\n正在还原数据库!");
            }
            //这里一定要是master数据库,而不能是要还原的数据库,因为这样便变成了有其它进程
            //占用了数据库。
            string constr = @"Data Source=.;Initial Catalog=master;User ID=sa;pwd =sa";
            string path = backfile;
            string BACKUP = String.Format("RESTORE DATABASE {0} FROM DISK = '{1}' WITH REPLACE", database, path);
            SqlConnection con = new SqlConnection(constr);
            SqlCommand cmd = new SqlCommand(BACKUP, con);
            con.Open();
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ee)
            {
                //throw(ee);
                return "还原失败";
                //MessageBox.Show("还原失败");
 
            }
            finally
            {
                con.Close();
            }
            return "还原成功";
 
        }

 

 

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网