public static void BackupDatabase() { string backupFileName = Commons.DataBasePath + DateTime.Now.ToString("yyyy-MM-") + "BackupDatabase.mdb", repariFileName = Commons.DataBasePath + "RepairDatabase.mdb"; try { BAYMYO.UI.FileIO.CreateDirectory(Commons.DataBasePath); //YEDEKLEME YAPMADAN ONCE VERITABANININ YEDEGINI ALIYORUZ! if (System.IO.File.Exists(backupFileName)) { System.IO.File.Delete(backupFileName); } System.IO.File.Copy(Commons.AppSettings.DATABASE, backupFileName, true); //REPAIR ISLEMI JRO.JetEngine je = new JRO.JetEngine(); je.CompactDatabase(ConnectionStringName, string.Format("Provider=Microsoft.Jet.Oledb.4.0;Data Source={0};Jet OLEDB:Engine Type=5", repariFileName)); //YEDEKLEME YAPILAN DB TEKRAR ALMA ISLEMI if (System.IO.File.Exists(backupFileName)) { System.IO.File.Delete(backupFileName); } System.IO.File.Move(repariFileName, backupFileName); Commons.Status(L.VeritabaniYedeklemeIslemi); } catch (Exception ex) { Commons.Status(Commons.GetErrorCode("CMN", 13) + ex.Message); } }
/// <summary> /// MBD compact method (c) 2004 Alexander Youmashev /// !!IMPORTANT!! /// !make sure there's no open connections /// to your db before calling this method! /// !!IMPORTANT!! /// </summary> /// <param name="connectionString">connection string to your db</param> /// <param name="mdwfilename">FULL name /// of an MDB file you want to compress.</param> //public static void CompactAccessDB(string connectionString, string mdwfilename) //{ // object[] oParams; // //create an inctance of a Jet Replication Object // object objJRO = // Activator.CreateInstance(Type.GetTypeFromProgID("JRO.JetEngine")); // //filling Parameters array // //cnahge "Jet OLEDB:Engine Type=5" to an appropriate value // // or leave it as is if you db is JET4X format (access 2000,2002) // //(yes, jetengine5 is for JET4X, no misprint here) // oParams = new object[] { connectionString, "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\tempdb.mdb;Jet OLEDB:Engine Type=5"}; // //invoke a CompactDatabase method of a JRO object // //pass Parameters array // objJRO.GetType().InvokeMember("CompactDatabase", // System.Reflection.BindingFlags.InvokeMethod, // null, // objJRO, // oParams); // //database is compacted now // //to a new file C:\\tempdb.mdw // //let's copy it over an old one and delete it // System.IO.File.Delete(mdwfilename); // System.IO.File.Move("C:\\tempdb.mdb", mdwfilename); // //clean up (just in case) // System.Runtime.InteropServices.Marshal.ReleaseComObject(objJRO); // objJRO = null; //} //public static void CompactMyTime() //{ // //Add a reference to "Microsoft Jet and Replication Objects 2.6 Library" (COM component) // string FileSource = "MyAccessFile.mdb"; // string SourceConnection = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + FileSource; // string DestConnection = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + "FileTmp.mdb"; // if (System.IO.File.Exists("FileTmp.mdb")) // System.IO.File.Delete("FileTmp.mdb"); // JRO.JetEngineClass objJet = new JRO.JetEngineClass(); // objJet.CompactDatabase(SourceConnection, DestConnection); // System.IO.File.Delete(FileSource); // System.IO.File.Move("FileTmp.mdb", FileSource); // } public static string CompactDatabase(string dbConnectionStr, string sourcePath) { JRO.JetEngine objJetEngine = new JRO.JetEngine(); if (dbConnectionStr.Contains("|DataDirectory|")) { dbConnectionStr = dbConnectionStr.Replace("|DataDirectory|", Path.GetDirectoryName(Application.ExecutablePath)); } string TargetConnection = dbConnectionStr.Replace("mytime.mdb", "myTimeRpr.mdb"); string targetPath = sourcePath.Replace("mytime.mdb", "myTimeRpr.mdb"); try { if (System.IO.File.Exists(targetPath)) { System.IO.File.Delete(targetPath); } System.IO.File.Move(sourcePath, targetPath); // take existing mdb rename it to old objJetEngine.CompactDatabase(TargetConnection, dbConnectionStr); // If all is good your done return("Success"); } catch (Exception ex) { // log exception Logging.TextLog.LogErr(ex.ToString()); // copy mdb from target to source to keep running without a C&R Database System.IO.File.Move(targetPath, sourcePath); // take existing mdb rename it to old return(ex.Message); } finally { objJetEngine = null; } }
/// <summary> /// 压缩Access数据库(2003版) /// </summary> /// <param name="sourceDbName">源数据库名称(包含扩展名.mdb)</param> /// <param name="sourceDbPwd">源数据库密码</param> /// <returns>返回值(true-成功,false-失败)</returns> public static bool CompressAccess(string sourceDbName, string sourceDbPwd) { string tmpDbName = @"$$$.mdb"; string sourceConnection = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= {0:S};" + "Jet OLEDB:Database Password= {1:S}", sourceDbName, sourceDbPwd); string destConnection = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= {0:S};" + "Jet OLEDB:Database Password= ", tmpDbName, sourceDbPwd); try { JRO.JetEngine databaseEngine = new JRO.JetEngine(); //压缩 databaseEngine.CompactDatabase(sourceConnection, destConnection); //将压缩后的数据库覆盖原数据库 System.IO.File.Copy(tmpDbName, sourceDbName, true); //删除压缩后的临时数据库 System.IO.File.Delete(tmpDbName); return(true); } catch (Exception ex) { CLDC_DataCore.Function.ErrorLog.Write(ex); return(false); } }
private bool backupDatabase(ref string lDatabase) { bool functionReturnValue = false; JRO.JetEngine jetEngine = default(JRO.JetEngine); string strSourceConnect = null; string strDestConnect = null; Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); fso.CopyFile(modRecordSet.serverPath + "" + lDatabase + ".mdb", modRecordSet.serverPath + "" + lDatabase + ".bk0", true); // ERROR: Not supported in C#: OnErrorStatement if (fso.FileExists(modRecordSet.serverPath + "" + lDatabase + ".bak")) { fso.DeleteFile(modRecordSet.serverPath + "" + lDatabase + ".bak", true); } strSourceConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + modRecordSet.serverPath + "" + lDatabase + ".mdb;User Id=liquid;Password=lqd;Jet OLEDB:System Database=" + modRecordSet.serverPath + "Secured.mdw"; strDestConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + modRecordSet.serverPath + "" + lDatabase + ".bak;User Id=liquid;Password=lqd;Jet OLEDB:System Database=" + modRecordSet.serverPath + "Secured.mdw"; jetEngine = new JRO.JetEngine(); // Compact and encrypt the database specified by strSourceDB // to the name and path specified by strDestDB. jetEngine.CompactDatabase(strSourceConnect, strDestConnect); //UPGRADE_NOTE: Object jetEngine may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"' jetEngine = null; fso.DeleteFile(modRecordSet.serverPath + "" + lDatabase + ".mdb"); fso.CopyFile(modRecordSet.serverPath + "" + lDatabase + ".bak", modRecordSet.serverPath + "" + lDatabase + ".mdb", true); modRecordSet.openConnection(); saveDatabase(ref lDatabase); functionReturnValue = true; return(functionReturnValue); backupDatabase_Error: fso.CopyFile(modRecordSet.serverPath + "" + lDatabase + ".bk0", modRecordSet.serverPath + "" + lDatabase + ".mdb", true); modRecordSet.openConnection(); functionReturnValue = false; return(functionReturnValue); }
/// <summary> /// MBD compact method (c) 2004 Alexander Youmashev /// !!IMPORTANT!! /// !make sure there's no open connections /// to your db before calling this method! /// !!IMPORTANT!! /// </summary> /// <param name="connectionString">connection string to your db</param> /// <param name="mdwfilename">FULL name /// of an MDB file you want to compress.</param> public static void CompactAccessDB(string connectionString, string mdwfilename) { JRO.JetEngine jro = new JRO.JetEngine(); string OldDb = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + mdwfilename; string NewDb = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + mdwfilename + ".tmp"; try { jro.CompactDatabase(OldDb, NewDb); Console.WriteLine("Finalizó la compactación de la base de datos"); System.IO.File.Delete(mdwfilename); System.IO.File.Move(mdwfilename + ".tmp", mdwfilename); } catch (Exception e) { } }
/// --------------------------------------------------------------------- /// <summary> /// MDBファイルを最適化する </summary> /// --------------------------------------------------------------------- private void mdbCompact() { try { JRO.JetEngine jro = new JRO.JetEngine(); string OldDb = Properties.Settings.Default.mdbOlePath; string NewDb = Properties.Settings.Default.mdbPathTemp; jro.CompactDatabase(OldDb, NewDb); //今までのバックアップファイルを削除する System.IO.File.Delete(Properties.Settings.Default.mdbPath + global.MDBBACK); //今までのファイルをバックアップとする System.IO.File.Move(Properties.Settings.Default.mdbPath + global.MDBFILE, Properties.Settings.Default.mdbPath + global.MDBBACK); //一時ファイルをMDBファイルとする System.IO.File.Move(Properties.Settings.Default.mdbPath + global.MDBTEMP, Properties.Settings.Default.mdbPath + global.MDBFILE); } catch (Exception e) { MessageBox.Show("MDB最適化中" + Environment.NewLine + e.Message, "エラー", MessageBoxButtons.OK); } }
private bool backupDatabase(ref string lDatabase) { bool functionReturnValue = false; JRO.JetEngine jetEngine = default(JRO.JetEngine); string strSourceConnect = null; string strDestConnect = null; Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); fso.CopyFile(modRecordSet.serverPath + "" + lDatabase + ".mdb", modRecordSet.serverPath + "" + lDatabase + ".bk0", true); // ERROR: Not supported in C#: OnErrorStatement if (fso.FileExists(modRecordSet.serverPath + "" + lDatabase + ".bak")) { fso.DeleteFile(modRecordSet.serverPath + "" + lDatabase + ".bak", true); } strSourceConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + modRecordSet.serverPath + "" + lDatabase + ".mdb;User Id=liquid;Password=lqd;Jet OLEDB:System Database=" + modRecordSet.serverPath + "Secured.mdw"; strDestConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + modRecordSet.serverPath + "" + lDatabase + ".bak;User Id=liquid;Password=lqd;Jet OLEDB:System Database=" + modRecordSet.serverPath + "Secured.mdw"; jetEngine = new JRO.JetEngine(); // Compact and encrypt the database specified by strSourceDB // to the name and path specified by strDestDB. jetEngine.CompactDatabase(strSourceConnect, strDestConnect); //UPGRADE_NOTE: Object jetEngine may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"' jetEngine = null; fso.DeleteFile(modRecordSet.serverPath + "" + lDatabase + ".mdb"); fso.CopyFile(modRecordSet.serverPath + "" + lDatabase + ".bak", modRecordSet.serverPath + "" + lDatabase + ".mdb", true); modRecordSet.openConnection(); saveDatabase(ref lDatabase); functionReturnValue = true; return functionReturnValue; backupDatabase_Error: fso.CopyFile(modRecordSet.serverPath + "" + lDatabase + ".bk0", modRecordSet.serverPath + "" + lDatabase + ".mdb", true); modRecordSet.openConnection(); functionReturnValue = false; return functionReturnValue; }
/// <summary> /// Compact the database mainly Access database(.mdb) and save as specified destination file. /// </summary> ///<param name="sourceDBConnection"> Source database connection</param> /// <param name="destFilePath">destination file name with path.</param> /// <param name="disposeConnection"> Set true when calling this methods for finish process otherwise false.For only saving the database, pass False and for finish , pass true. </param> /// <returns>true, if success.</returns> /// <remarks>Before calling this function,dont dispose source database connection </remarks> public static bool CompactDataBase(ref DIConnection sourceDBConnection, DIQueries dbQueries, string destFilePath, bool disposeConnection) { bool RetVal = false; bool IsFileOpen = false; DIConnectionDetails SourceDBConnectionDetails; DBMetadataTableBuilder DBMetadataTable; DIDatabase DBDatabase; string SourceDBNameWPath; JRO.JetEngine je; string DataPrefix = string.Empty; DI7MetadataCategoryBuilder DI7MetadataCategory; // -- NOTE: USE sDestFile only when sDestFile <> sSourceDB try { if (sourceDBConnection != null && !string.IsNullOrEmpty(destFilePath)) { //Drop index for ut_data table for IUSNID, areanid column DIDatabase.DropDefaultIndex(sourceDBConnection); // update counts in DBMetadata table( only if database/template is in DI6 format) if (dbQueries == null) { DataPrefix = sourceDBConnection.DIDataSetDefault(); dbQueries = new DIQueries(DataPrefix, sourceDBConnection.DILanguageCodeDefault(DataPrefix)); } DBMetadataTable = new DBMetadataTableBuilder(sourceDBConnection, dbQueries); if (DBMetadataTable.IsDBMetadataTableExists()) { DBMetadataTable.GetNUpdateCounts(); } //Updating XSLT from Resourse File into database. DI7MetadataCategory = new DI7MetadataCategoryBuilder(sourceDBConnection, dbQueries); DI7MetadataCategory.UpdateXSLT(dbQueries.DataPrefix); // update database name in DB_Available table sourceDBConnection.InsertNewDBFileName(dbQueries.DataPrefix, DICommon.RemoveQuotes(System.IO.Path.GetFileName(destFilePath))); if (DIDatabase.SeperateDataValueColumn) { // Check orgTextual_Data_value exists or not. If column exists then move textual & numeric values into their respective column. DIDataValueHelper.SeparateTextualandNemericData(sourceDBConnection, dbQueries); } // update indicator unit and subgroup nids in Data table DBDatabase = new DIDatabase(sourceDBConnection, dbQueries); DBDatabase.UpdateIndicatorUnitSubgroupNIDsInData(); // remove FootnoteNId inconsistency. (replace 0 or null FootnoteNId by -1 in UT_data table). DBDatabase.RemoveFootnoteNIdsInconsistencyInData(); // Update auto calculated columns ( IC table - Publisher, Year & title ,Indicator table- Data_Exists, area table - data_exist, IUS table - subgroup_nids & data_exist) into the database/template DBDatabase.UpdateAutoCalculatedFieldsInTables(); // Update auto calculated column of DI7 DBDatabase.UpdateAutoCalculatedDI7FieldsInTables(); //Update those subgroupVals which is not associated with any subgroup type.Then insert association with others for those subgroup DBDatabase.UpdateSubgroupValsInOthersSGDimensionInTables(); //Create index for ut_data table for IUSNID, areanid column DIDatabase.CreateDefaultIndex(sourceDBConnection); // dispose source database connection SourceDBConnectionDetails = sourceDBConnection.ConnectionStringParameters; SourceDBNameWPath = SourceDBConnectionDetails.DbName; sourceDBConnection.Dispose(); System.Threading.Thread.Sleep(10); try { if (File.Exists(destFilePath)) { File.SetAttributes(destFilePath, FileAttributes.Normal); File.Delete(destFilePath); } } catch { } //-- Copy SourceFile to temp file so that any existing connection on database shall not stop compact database process. //string TempFile = DICommon.GetValidFileName(DateTime.Now.ToString()) + Path.GetExtension(SourceDBNameWPath); //File.Copy(SourceDBNameWPath, TempFile, true); try { // compacting the database je = new JRO.JetEngine(); je.CompactDatabase("Data Source=\"" + SourceDBNameWPath + "\";Jet OLEDB:Database Password="******"Data Source=\"" + destFilePath + "\";Jet OLEDB:Database Password="******"Database already exists")) IsFileOpen = true; } // reconnect to source database if (!disposeConnection) { sourceDBConnection = new DIConnection(SourceDBConnectionDetails); } if (IsFileOpen == false) RetVal = true; } } catch (Exception ex) { RetVal = false; ExceptionFacade.ThrowException(ex); } return RetVal; }
/// <summary> /// Compact the database mainly Access database(.mdb) and save as specified destination file. /// </summary> public bool CompactDataBase(ref DIConnection sourceDBConnection) { bool RetVal = false; string SourceFilePath = string.Empty; DIConnectionDetails SourceDBConnectionDetails; JRO.JetEngine je; string DataPrefix = string.Empty; try { if (sourceDBConnection != null) { // dispose source database connection SourceDBConnectionDetails = sourceDBConnection.ConnectionStringParameters; SourceFilePath = SourceDBConnectionDetails.DbName; sourceDBConnection.Dispose(); System.Threading.Thread.Sleep(10); //try //{ // if (File.Exists(destFilePath)) // { // File.SetAttributes(destFilePath, FileAttributes.Normal); // File.Delete(destFilePath); // } //} //catch { } // Copy SourceFile to temp file string TempFile = DICommon.GetValidFileName(DateTime.Now.ToString()) + Path.GetExtension(SourceFilePath); // File.Copy(SourceDBNameWPath, TempFile, true); // compacting the database je = new JRO.JetEngine(); je.CompactDatabase("Data Source=\"" + SourceFilePath + "\";Jet OLEDB:Database Password="******"Data Source=\"" + TempFile + "\";Jet OLEDB:Database Password=" + SourceDBConnectionDetails.Password); je = null; // copy temp file to source file System.IO.File.Copy(TempFile, SourceFilePath, true); // reconnect to source database sourceDBConnection = new DIConnection(SourceDBConnectionDetails); RetVal = true; } } catch (Exception ex) { RetVal = false; throw new ApplicationException(ex.ToString()); } return RetVal; }