用C#压缩和修复Access数据库-Access数据库工具类

///
    /// Access数据库工具类
    ///

    public class AccessDbTool
    {
        ///
        /// 压缩修复数据库工具
        /// 注:考虑到数据库已被打开的情况,此处方案为先COPY原数据库,再压缩COPY数据库,再覆盖原数据库,再删除临时数据库
        ///

        /// 数据库物理路径
        /// 数据库密码
        ///
        public static bool compactAccessDB(string path, string password)
        {
            if (path == null || password == null) return false;
            if (path.Equals("")) return false;

            string path2 = path.Substring(0, path.LastIndexOf('.')) + "tmp.mdb";
            string path3 = path.Substring(0, path.LastIndexOf('.')) + "copy.mdb";
            File.Copy(path, path3, true);

            string dbConn3, dbConn2;
            dbConn3 = "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=" + password + ";Data Source=" + path3;
            dbConn2 = "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=" + password + ";Data Source=" + path2 + ";Jet OLEDB:Engine Type=5";

            try
            {
                JRO.JetEngine dbEngin = new JRO.JetEngine();
                dbEngin.CompactDatabase(dbConn3, dbConn2);//压缩

                File.Copy(path2, path, true);//将压缩后的数据库覆盖原数据库
                File.Delete(path2);//删除压缩后的数据库
                File.Delete(path3);//删除压缩前的Copy数据库

                return true;
            }
            catch (Exception e)
            {
                RouseCMS.log.Log.Error("AccessDbTool.compactAccessDB" + " " + e.Message);
                RouseCMS.log.Log.Error(e.StackTrace, true);
                return false;
            }
        }
    }

你可能感兴趣的:(C#(winform))