Exemple #1
0
        public bool OpenDatabase(string DBname = "", string DBpassword = "")
        {
            if (DBname == "")
            {
                // open last database
                DBname     = mf.Tls.GetProperty("LastDatabase");
                DBpassword = mf.Tls.GetProperty("LastPassword");
            }
            if (File.Exists(DBname))
            {
                try
                {
                    try
                    {
                        // close previous database
                        cDatabaseName = "";
                        cConnected    = false;
                        cDB.Close();
                    }
                    catch (Exception)
                    {
                    }
                    string DBvalid = CheckDatabase(DBname);
                    if (DBvalid == "true")
                    {
                        cDB = cDBE.OpenDatabase(DBname, DAO.DriverPromptEnum.dbDriverNoPrompt, false, ";pwd=" + DBpassword);
                        mf.Tls.SaveProperty("LastDatabase", DBname);
                        mf.Tls.SaveProperty("LastPassword", DBpassword);
                        cDatabaseName = Path.GetFileName(DBname);
                        cConnected    = true;

                        // record database directory
                        mf.Tls.DataFolder = Path.GetDirectoryName(DBname);

                        // check database size
                        TrimRecords(cDB);

                        // raise database connected event
                        DBconnected?.Invoke();

                        return(true);
                    }
                    else
                    {
                        mf.Tls.WriteErrorLog("clsDatabase: OpenDatabase: " + DBvalid);
                        mf.Tls.TimedMessageBox("Database not valid.", DBvalid);
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    mf.Tls.WriteErrorLog("clsDatabase: OpenDatabase: " + ex.Message);
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
    private void FillDefaultLine(Control container, string[] ids)
    {
        string dbpath = GetDirectory() + userDir + MAIN_USER_DATABASE;

        DAO.Database dat = null;

        Control[] txtNewRecord = new Control[FIELDS.Length];

        try
        {
            DAO.DBEngine daoEngine = new DAO.DBEngine();
            dat = daoEngine.OpenDatabase(dbpath, false, false, "");
            DAO.TableDef tableDef = dat.TableDefs[TABLE_NAME];
            for (int i = 1; i < FIELDS.Length; i++)
            {
                if (!FIELDS[i].Equals("opnam1") && !FIELDS[i].Equals("opnam2"))
                { // aliases which are not in the database
                    string defaultValue = (string)tableDef.Fields[FIELDS[i]].Properties["DefaultValue"].Value;
                    if (defaultValue != null && !defaultValue.Equals("\" \"") && !defaultValue.Equals(""))
                    {
                        txtNewRecord[i] = container.FindControl(ids[i]);
                        if (txtNewRecord[i] != null)
                        {
                            defaultValue = MyUtilities.clean(defaultValue, '"');
                            if (COMBOS[i])
                            {
                                ((AjaxControlToolkit.ComboBox)txtNewRecord[i]).Text = defaultValue;
                            }
                            else if (CHECKBOXES[i])
                            {
                                ((CheckBox)txtNewRecord[i]).Checked = defaultValue.ToString().Equals("-1");
                            }
                            else if (!((TextBox)txtNewRecord[i]).Enabled)
                            {
                                defaultValue = null;
                            }
                            else
                            {
                                ((TextBox)txtNewRecord[i]).Text = defaultValue;
                            }
                        }
                    }
                }
            }


            dat.Close();
        }
        catch (Exception)
        {
            try
            {
                dat.Close();
            }
            catch (Exception) { }
        }
    }
Exemple #3
0
        protected override int Connect_PerformanceTest(string strConnection)
        {
            // Version for performance testing
            int recordsRead = 0;

            DAO.DBEngine dbEngine = new DAO.DBEngine();
            dbEngine.Idle(DAO.IdleEnum.dbRefreshCache);

            DAO.Database  db = dbEngine.OpenDatabase(strConnection, false, false);
            DAO.Recordset rs = db.OpenRecordset(
                m_cfgDatabase.querySELECT.Replace("?", m_cfgDatabase.paramValue.ToString()),
                DAO.RecordsetTypeEnum.dbOpenDynaset,
                DAO.RecordsetOptionEnum.dbReadOnly);
            if (!(rs.BOF && rs.EOF))
            {
                // Go through each record in the RecordSet; for this performance version just count
                // the number of records read
                rs.MoveFirst();
                dbEngine.Idle(DAO.IdleEnum.dbFreeLocks);
                while (!rs.EOF)
                {
                    recordsRead++;
                    rs.MoveNext();
                    dbEngine.Idle(DAO.IdleEnum.dbFreeLocks);
                }
                rs.Close();
            }

            db.Close();
            return(recordsRead);
        }
Exemple #4
0
        protected override void Connect_Stats(string strConnection)
        {
            // Generate some statistics about the selected database (see "Northwind_DAO.Connect_Stats()"
            // for additional information)
            string dbName = m_utilsDAO.GetDbName(strConnection);
            DAO.DBEngine dbEngine = new DAO.DBEngine();
            dbEngine.Idle(DAO.IdleEnum.dbRefreshCache);
            DAO.Database db = dbEngine.OpenDatabase(strConnection, false, false);

            // Tables
            if (db.TableDefs.Count > 0)
            {
                // Note: Access 97 databases tend to come with
                Console.WriteLine("    ({0} tables in {1})", db.TableDefs.Count, dbName);
                foreach (DAO.TableDef td in db.TableDefs)
                {
                    Console.WriteLine("      {0}", td.Name);
                }
            }
            else
                Console.WriteLine("    (There are no tables in {0}!)", db.Name);

            db.Close();
            Console.WriteLine();
        }
Exemple #5
0
        public List <string> GetFields(string strConnection, string strTable)
        {
            // Return a list of the columns in the supplied table
            List <string> columns = new List <string>();

            DAO.DBEngine dbEngine = new DAO.DBEngine();
            dbEngine.Idle(DAO.IdleEnum.dbRefreshCache);
            DAO.Database db = dbEngine.OpenDatabase(strConnection, false, false);
            if (db.TableDefs.Count > 0)
            {
                try
                {
                    if (db.TableDefs[strTable].Fields.Count > 0)
                    {
                        columns.Add(m_fieldHeader);
                        foreach (DAO.Field fd in db.TableDefs[strTable].Fields)
                        {
                            columns.Add(string.Format(Schema_Header_Column_Formatting,
                                                      fd.Name,
                                                      fd.Type,
                                                      GetFieldTypeAsString(fd),
                                                      fd.Size,
                                                      fd.Required));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(UtilitiesGeneral.FormatException(
                                          this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                }
            }
            db.Close();
            return(columns);
        }
Exemple #6
0
        public List <string> GetTables(string strConnection, bool removeSysTables = false)
        {
            // Return a list of the tables in the supplied database
            // Note: Access databases use a number System tables used to manage the database, such as:
            // * MSysAccessObjects
            // * MSysACEs
            // * MSysCmdbars
            // * MSysIMEXColumns
            // * MSysIMEXSpecs
            // * MSysObjects
            // * MSysQueries
            // * MSysRelationships
            List <string> tables = new List <string>();

            DAO.DBEngine dbEngine = new DAO.DBEngine();
            dbEngine.Idle(DAO.IdleEnum.dbRefreshCache);
            DAO.Database db = dbEngine.OpenDatabase(strConnection, false, false);
            if (db.TableDefs.Count > 0)
            {
                foreach (DAO.TableDef td in db.TableDefs)
                {
                    if ((!removeSysTables) ||
                        (!td.Name.StartsWith("MSys")))
                    {
                        tables.Add(td.Name);
                    }
                }
            }
            db.Close();
            return(tables);
        }
Exemple #7
0
        /// <summary>
        /// 创建一个 Access 数据库实例(创建 mdb 文件)
        /// </summary>
        /// <param name="fileName">欲创建的数据库文件名</param>
        /// <returns>一个 Access 实例数据库</returns>
        public static AccessDb CreateDbInstance(string fileName)
        {
            DAO.DBEngine daoDBE = new DAO.DBEngine();
            DAO.Database daoDB  = daoDBE.CreateDatabase(fileName, ";LANGID=0x0804;CP=936;COUNTRY=0;", DAO.DatabaseTypeEnum.dbVersion40);
            daoDB.Close();

            return(new AccessDb(fileName));
        }
Exemple #8
0
        public bool TableIsExist(string tableName)
        {
            DAO.DBEngine daoDBE = new DAO.DBEngine();
            DAO.Database daoDB  = null;
            daoDB = daoDBE.OpenDatabase(this.FileName, false, false, "MS ACCESS;PWD=" + this.Password);
            DAO.TableDefs daoTables = daoDB.TableDefs;

            foreach (DAO.TableDef daoTable in daoDB.TableDefs)
            {
                if (daoTable.Name.Equals(tableName))
                {
                    daoDB.Close();
                    return(true);
                }
            }

            daoDB.Close();
            return(false);
        }
Exemple #9
0
        private string CheckDatabase(string DBname)
        {
            // check database type, version
            string Result = "";

            try
            {
                cDB = cDBE.OpenDatabase(DBname, DAO.DriverPromptEnum.dbDriverNoPrompt, false, "");
                DAO.Recordset RS;
                string        SQL = "select * from tblProps";
                RS = cDB.OpenRecordset(SQL);
                if (RS.EOF)
                {
                    RS.Close();
                    cDB.Close();
                    Result = "No Data.";
                }
                else
                {
                    // check database type
                    string ReportedType    = (string)(RS.Fields["dbType"].Value ?? "");
                    short  ReportedVersion = (short)(RS.Fields["dbVersion"].Value ?? 0);
                    RS.Close();
                    cDB.Close();
                    if (ReportedType == DBtype)
                    {
                        // check version
                        Result = CheckVersion(ReportedVersion, DBname);
                    }
                    else
                    {
                        Result = "Wrong database type.";
                    }
                }
            }
            catch (Exception ex)
            {
                mf.Tls.WriteErrorLog("clsDatabase:CheckDatabase: " + ex.Message);
            }
            return(Result);
        }
Exemple #10
0
        protected override void Connect_Read(string strConnection)
        {
            // Use the DAO::DBEngine to open an Access database and read recordsets

            // Note: On one machine running Windows 10 and Office 365, the DBEngine had these details:
            // * TypeLib = {4AC9E1DA-5BAD-4AC7-86E3-24F4CDCECA28}
            // * Name = Microsoft Office 16.0 Access Database Engine Object Library
            // * Assembly = Microsoft.Office.Interop.Access.Dao, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C
            // * Path = C:\Program Files\Microsoft Office\root\VFS\ProgramFilesCommonX64\Microsoft Shared\Office16\ACEDAO.DLL
            DAO.DBEngine dbEngine = new DAO.DBEngine();
            dbEngine.Idle(DAO.IdleEnum.dbRefreshCache);

            DAO.Database db = dbEngine.OpenDatabase(strConnection, false, false);
            DAO.Recordset rs = db.OpenRecordset(
                m_cfgDatabase.querySELECT,
                DAO.RecordsetTypeEnum.dbOpenDynaset,
                DAO.RecordsetOptionEnum.dbReadOnly);
            if (!(rs.BOF && rs.EOF))
            {
                // Go through each record in the RecordSet, writing the result to the console window
                Simple_Members rsMember = new Simple_Members();
                Console.WriteLine(rsMember.GetRecordHeader());

                int recordsRead = 0;
                rs.MoveFirst();
                dbEngine.Idle(DAO.IdleEnum.dbFreeLocks);
                while (!rs.EOF)
                {
                    recordsRead++;
                    try
                    {
                        ConvertRecordset(in rs, ref rsMember);
                        Console.WriteLine(rsMember.GetRecordAsString());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(UtilitiesGeneral.FormatException(
                            this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
                    }
                    rs.MoveNext();
                    dbEngine.Idle(DAO.IdleEnum.dbFreeLocks);
                }
                rs.Close();
                Console.WriteLine("    ({0} records)", recordsRead);
            }

            db.Close();
            Console.WriteLine();
        }
 public static void Main(string[] args)
 {
     try
     {
         if (args.Length == 0)
         {
             Console.WriteLine("Please enter an MS Access application path as a parameter!");
             return;
         }
         dbEngine = new DAO.DBEngine();
         database = dbEngine.OpenDatabase(args[0]);
         DAO.Property allowBypassKeyProperty = null;
         foreach (dao.Property property in database.Properties)
         {
             if (property.Name == "AllowBypassKey")
             {
                 allowBypassKeyProperty = property;
                 break;
             }
         }
         if (allowBypassKeyProperty == null)
         {
             allowBypassKeyProperty = database.CreateProperty("AllowBypassKey", DAO.DataTypeEnum.dbBoolean, false, true);
             database.Properties.Append(allowBypassKeyProperty);
             Console.WriteLine("AllowBypassKey Property has been added. It's Value is '" + allowBypassKeyProperty.Value + "'");
         }
         else
         {
             allowBypassKeyProperty.Value = !allowBypassKeyProperty.Value;
             Console.WriteLine("AllowBypassKey set to '" + allowBypassKeyProperty.Value + "'!");
         }
     }
     catch (Exception exception)
     {
         Console.WriteLine("Exception Message: " + exception.Message);
         Console.WriteLine("Inner Exception:" + exception.InnerException);
     }
     finally
     {
         database.Close();
         System.Runtime.InteropServices.Marshal.ReleaseComObject(database);
         database = null;
         System.Runtime.InteropServices.Marshal.ReleaseComObject(dbEngine);
         dbEngine = null;
         Console.WriteLine();
         Console.WriteLine("Press enter to continue ...");
         Console.ReadLine();
     }
 }
Exemple #12
0
        public void InsertDao()
        {
            object objOpt   = System.Reflection.Missing.Value;
            var    dbEngine = new DAO.DBEngine();

            DAO.Database  cdb = dbEngine.OpenDatabase(@"c:\Projects\С\Databases\Databases\dbproba.mdb", objOpt, false, objOpt);
            DAO.Recordset rec = cdb.OpenRecordset("Tabl1", DAO.RecordsetTypeEnum.dbOpenDynaset, DAO.RecordsetOptionEnum.dbSeeChanges, DAO.LockTypeEnum.dbOptimistic);
            rec.MoveFirst();
            MessageBox.Show(rec.Fields["s1"].Value.ToString());
            rec.AddNew();
            rec.Fields["s1"].Value = "ssssss";
            rec.Update();
            rec.Close();
            cdb.Close();
        }
Exemple #13
0
        protected override void Connect_Read(string strConnection)
        {
            // Use the DAO::DBEngine to open an Access database and read recordsets

            // Note: On one machine running Windows 10 and Office 365, the DBEngine had these details:
            // * TypeLib = {4AC9E1DA-5BAD-4AC7-86E3-24F4CDCECA28}
            // * Name = Microsoft Office 16.0 Access Database Engine Object Library
            // * Assembly = Microsoft.Office.Interop.Access.Dao, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C
            // * Path = C:\Program Files\Microsoft Office\root\VFS\ProgramFilesCommonX64\Microsoft Shared\Office16\ACEDAO.DLL
            DAO.DBEngine dbEngine = new DAO.DBEngine();
            dbEngine.Idle(DAO.IdleEnum.dbRefreshCache);

            DAO.Database  db = dbEngine.OpenDatabase(strConnection, false, false);
            DAO.Recordset rs = db.OpenRecordset(
                m_cfgDatabase.querySELECT.Replace("?", m_cfgDatabase.paramValue.ToString()),
                DAO.RecordsetTypeEnum.dbOpenDynaset,
                DAO.RecordsetOptionEnum.dbReadOnly);
            if (!(rs.BOF && rs.EOF))
            {
                // Go through each record in the RecordSet, writing the result to the console window
                int recordsRead = 0;
                Console.WriteLine("\t{0}{1}{2}",
                                  Northwind_Products.colProductID.PadRight(Northwind_Products.colProductIDWidth),
                                  Northwind_Products.colUnitPrice.PadRight(Northwind_Products.colUnitPriceWidth),
                                  Northwind_Products.colProductName);

                rs.MoveFirst();
                dbEngine.Idle(DAO.IdleEnum.dbFreeLocks);
                while (!rs.EOF)
                {
                    recordsRead++;
                    Console.WriteLine("\t{0}{1}{2}",
                                      ((int)m_utilsDAO.SafeGetFieldValue(rs, Northwind_Products.colProductID)).ToString().PadRight(Northwind_Products.colProductIDWidth),
                                      ((decimal)m_utilsDAO.SafeGetFieldValue(rs, Northwind_Products.colUnitPrice)).ToString("0.00").PadRight(Northwind_Products.colUnitPriceWidth),
                                      (m_utilsDAO.SafeGetFieldValue(rs, Northwind_Products.colProductName)).ToString());
                    rs.MoveNext();
                    dbEngine.Idle(DAO.IdleEnum.dbFreeLocks);
                }
                rs.Close();
                Console.WriteLine("    ({0} records)", recordsRead);
            }

            db.Close();
            Console.WriteLine();
        }
Exemple #14
0
        public override string GetDbName(string strConnection)
        {
            // Get the name of the database associated with the connection string
            string dbName = string.Empty;

            try
            {
                DAO.DBEngine dbEngine = new DAO.DBEngine();
                dbEngine.Idle(DAO.IdleEnum.dbRefreshCache);
                DAO.Database db = dbEngine.OpenDatabase(strConnection, false, false);
                dbName = db.Name;
                db.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(UtilitiesGeneral.FormatException(
                                      this.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message));
            }
            return(dbName);
        }
Exemple #15
0
        public void MegaInsertDao()
        {
            object objOpt   = System.Reflection.Missing.Value;
            var    dbEngine = new DAO.DBEngine();

            DAO.Database  cdb = dbEngine.OpenDatabase(@"dbproba.mdb", objOpt, false, objOpt);
            DAO.Recordset rec = cdb.OpenRecordset("Tabl3", DAO.RecordsetTypeEnum.dbOpenDynaset, DAO.RecordsetOptionEnum.dbSeeChanges, DAO.LockTypeEnum.dbOptimistic);
            DateTime      d   = DateTime.Now;

            for (int i = 1; i <= 10000; ++i)
            {
                rec.AddNew();
                rec.Fields["s1"].Value = i.ToString();
                rec.Fields["s2"].Value = "n";
                rec.Update();
            }
            rec.Close();
            cdb.Close();
            MessageBox.Show(DateTime.Now.Subtract(d).ToString());
        }
Exemple #16
0
        public void DummyOpenClose()
        {
            Console.WriteLine("    (Dummy open and close databases using DAO)");
            int    startTicks    = Environment.TickCount;
            string strConnection = string.Empty;

            DAO.DBEngine dbEngine = new DAO.DBEngine();
            DAO.Database db       = null;
            foreach (MSAccessDbType dbType in Enum.GetValues(typeof(MSAccessDbType)))
            {
                m_cfgDatabase.dbType = dbType;
                Console.WriteLine("  Testing: {0}", HelperGetAccessName(true));
                if (SetConnectionString(ref strConnection))
                {
                    db = dbEngine.OpenDatabase(strConnection, false, false);
                    db.Close();
                }
            }

            int elapsedTicks = (Environment.TickCount - startTicks);

            Console.WriteLine("    (Completed dummy open/close. Took {0}ms.)", elapsedTicks);
        }
Exemple #17
0
        protected override void Connect_Writeable(string strConnection)
        {
            // Use the DAO::DBEngine to open an Access database and write recordsets
            DAO.DBEngine dbEngine = new DAO.DBEngine();
            dbEngine.Idle(DAO.IdleEnum.dbRefreshCache);

            DAO.Database db       = dbEngine.OpenDatabase(strConnection, false, false);
            string       strQuery = m_cfgDatabase.querySELECT.Replace("?", m_cfgDatabase.paramValue.ToString());

            Console.Write("Open database read-only: ");
            DAO.Recordset rs = db.OpenRecordset(
                strQuery,
                DAO.RecordsetTypeEnum.dbOpenDynaset,
                DAO.RecordsetOptionEnum.dbReadOnly);
            if (!(rs.BOF && rs.EOF))
            {
                Console.WriteLine(m_utilsDAO.IsRecordUpdateable(rs));
                rs.Close();
            }

            Console.Write("Open database writeable: ");
            rs = db.OpenRecordset(
                strQuery,
                DAO.RecordsetTypeEnum.dbOpenDynaset);
            if (!(rs.BOF && rs.EOF))
            {
                Console.WriteLine(m_utilsDAO.IsRecordUpdateable(rs));
                Console.WriteLine();

                // Now go through all records and check various properties
                int recordsRead = 0;
                Console.WriteLine("  (Using the \"ProductName\" field as an example)");
                Console.WriteLine(
                    "#\tRequired\tValidateOnSet\tValidationRule\tValidationText\tSize\tValue");
                DAO.Field fd;
                rs.MoveFirst();
                while (!rs.EOF)
                {
                    recordsRead++;
                    fd = m_utilsDAO.SafeGetField(rs, "ProductName");
                    if (fd != null)
                    {
                        Console.WriteLine("{0}\t{1}\t\t{2}\t\t{3}\t\t{4}\t\t{5}\t{6}",
                                          recordsRead,
                                          fd.Required,
                                          m_utilsDAO.BoolFieldToString(fd.ValidateOnSet),
                                          m_utilsDAO.StringFieldToString(fd.ValidationRule),
                                          m_utilsDAO.StringFieldToString(fd.ValidationText),
                                          fd.Size,
                                          fd.Value);
                    }
                    else
                    {
                        Console.WriteLine("{0}(record is null)", recordsRead);
                    }

                    rs.MoveNext();
                }
                rs.Close();
            }

            db.Close();
            Console.WriteLine();
        }
Exemple #18
0
        private static DateTime CreateTableTime = DateTime.MinValue;    //最后一次创建表的时间

        #region IDb 成员

        public void CreateTable(Table table, string tableName)
        {
            CreateTableTime = DateTime.Now;
            if (tableName == null || tableName.Length == 0)
            {
                tableName = table.Code;
            }

            DAO.DBEngine daoDBE = new DAO.DBEngine();
            DAO.Database daoDB  = null;
            daoDB = daoDBE.OpenDatabase(this.FileName, false, false, "MS ACCESS;PWD=" + this.Password);
            DAO.TableDefs daoTables = daoDB.TableDefs;

            foreach (DAO.TableDef daoT in daoDB.TableDefs)
            {
                if (daoT.Name.Equals(tableName))
                {
                    daoTables.Delete(tableName);                          //删除现存的表
                }
            }

            DAO.TableDef daoTable            = daoDB.CreateTableDef(tableName, 0, "", "");
            string       strPrimaryKeyFields = "";

            foreach (Column _Column in table.Columns)
            {
                DAO.Field daoField = new DAO.Field();
                daoField.Name = _Column.Code;

                switch (_Column.DataType)
                {
                case DataTypeOptions.Int:
                    daoField.Type = Convert.ToInt16(DAO.DataTypeEnum.dbLong);
                    break;

                case DataTypeOptions.Long:
                case DataTypeOptions.Decimal:
                    daoField.Type = Convert.ToInt16(DAO.DataTypeEnum.dbDouble);
                    break;

                case DataTypeOptions.VarChar:
                    if (_Column.DataLength > 255)
                    {
                        daoField.Type            = Convert.ToInt16(DAO.DataTypeEnum.dbMemo);
                        daoField.AllowZeroLength = true;
                    }
                    else
                    {
                        daoField.Type            = Convert.ToInt16(DAO.DataTypeEnum.dbText);
                        daoField.Size            = _Column.DataLength;
                        daoField.AllowZeroLength = true;
                    }
                    break;

                case DataTypeOptions.Text:
                    daoField.Type            = Convert.ToInt16(DAO.DataTypeEnum.dbMemo);
                    daoField.AllowZeroLength = true;
                    break;

                case DataTypeOptions.File:
                    daoField.Type = Convert.ToInt16(DAO.DataTypeEnum.dbLongBinary);
                    break;

                default:
                    throw new Exception("尚未实现的数据类型 " + _Column.DataType);
                }
                daoField.Required = _Column.IsNotNull;

                if (_Column.IsPrimaryKey)
                {
                    strPrimaryKeyFields += _Column.Code + ";";
                }

                daoTable.Fields.Append(daoField);
            }

            daoDB.TableDefs.Append(daoTable);

            if (table.Name != null && table.Name.Length > 0)
            {
                DAO.Property daoTableProperty = daoTable.CreateProperty("Description", DAO.DataTypeEnum.dbText, table.Name, 0);
                daoTable.Properties.Append(daoTableProperty);
            }

            foreach (Column _Column in table.Columns)
            {
                if (_Column.Name != null && _Column.Name.Length > 0)
                {
                    DAO.Field    daoField          = daoTable.Fields[_Column.Code];
                    DAO.Property daoColumnProperty = daoField.CreateProperty("Description", DAO.DataTypeEnum.dbText, _Column.Name, 0);
                    daoField.Properties.Append(daoColumnProperty);
                }
            }

            if (strPrimaryKeyFields.Length > 0)
            {
                DAO.Index daoIndex = daoTable.CreateIndex("PK_" + tableName);
                daoIndex.Fields  = strPrimaryKeyFields;
                daoIndex.Primary = true;
                daoIndex.Unique  = true;
                daoTable.Indexes.Append(daoIndex);
            }

            foreach (Index _Index in table.Indexs)
            {
                string strKeyFields = "";
                foreach (Column _KeyColumn in _Index.Columns)
                {
                    strKeyFields += "+" + _KeyColumn.Code + ";";
                }

                if (strKeyFields.Length > 0)
                {
                    DAO.Index daoIndex = daoTable.CreateIndex(_Index.Code);
                    daoIndex.Fields  = strKeyFields;
                    daoIndex.Primary = false;
                    daoIndex.Unique  = false;

                    daoTable.Indexes.Append(daoIndex);
                }
            }

            daoDB.Close();

            TimeSpan ts = DateTime.Now - CreateTableTime;

            if (ts.Seconds < 2)
            {
                System.Threading.Thread.Sleep(10000);    //Access 数据表创建后需要一段时间才能访问。
            }
        }
Exemple #19
0
        private string CheckVersion(short Ver, string DBname)
        {
            string SQL;

            DAO.Recordset RS;
            string        Result = "";

            if (Ver > cDBversion)
            {
                // higher version, program out of date
                Result = "Database version does not match, software out of date.";
            }
            else if (Ver == cDBversion)
            {
                Result = "true";
            }
            else
            {
                // lower version, update

                // close current database
                try
                {
                    cDB.Close();
                }
                catch (Exception)
                {
                }

                // copy base file to tmp file in data folder
                string NewPath  = mf.Tls.DataFolder + "\\NewTmp.mdb";
                string BasePath = mf.Tls.SettingsFolder + "\\TempMonBase.mdb";
                File.WriteAllBytes(NewPath, Properties.Resources.Base);
                FileInfo BaseFile = new FileInfo(BasePath);

                // copy current database to tmp file in data folder
                string TmpPath = mf.Tls.DataFolder + "\\OldTmp.mdb";
                try
                {
                    // delete tmp file, if it exists
                    File.Delete(TmpPath);
                }
                catch (Exception Ex)
                {
                    mf.Tls.WriteErrorLog("clsDatabase: CheckVersion: " + Ex.Message);
                }
                FileInfo OldFile = new FileInfo(DBname);
                OldFile.CopyTo(TmpPath);

                // open new tmp database and old tmp database
                DAO.Database DBnew = cDBE.OpenDatabase(NewPath, DAO.DriverPromptEnum.dbDriverNoPrompt, false, "");
                DAO.Database DBold = cDBE.OpenDatabase(TmpPath, DAO.DriverPromptEnum.dbDriverNoPrompt, false, "");

                // delete new database properties records
                SQL = "select * from tblProps";
                RS  = DBnew.OpenRecordset(SQL);
                while (!RS.EOF)
                {
                    RS.Delete();
                    RS.MoveNext();
                }
                RS.Close();

                // copy matching data from old database to new database
                if (CopyData(DBnew, DBold))
                {
                    // update database properties
                    SQL = "select * from tblProps";
                    RS  = DBnew.OpenRecordset(SQL);
                    if (RS.EOF)
                    {
                        RS.AddNew();
                    }
                    else
                    {
                        RS.Edit();
                    }
                    RS.Fields["dbType"].Value    = DBtype;
                    RS.Fields["dbVersion"].Value = cDBversion;
                    RS.Update();
                    RS.Close();

                    // copy new updated database to current database name
                    DBnew.Close();
                    DBold.Close();
                    File.Delete(DBname);    // delete current file
                    FileInfo NewFile = new FileInfo(NewPath);
                    NewFile.CopyTo(DBname); // copy new file to current file name
                    File.Delete(TmpPath);   // delete tmp copy of current file
                    File.Delete(NewPath);   // delete new file
                    Result = "true";
                }
                else
                {
                    // failed to copy, remove new database and tmp database
                    File.Delete(TmpPath);   // delete tmp copy of current file
                    File.Delete(NewPath);   // delete new file
                    Result = "Failed to update database version.";
                }
            }
            return(Result);
        }