Exemplo n.º 1
2
        private void MakeOwnedDBbgw_DoWork(object sender, DoWorkEventArgs e)
        {
            string DocLocation = System.Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Documents\\Magic Manager\\";
            if (!System.IO.Directory.Exists(DocLocation))
                System.IO.Directory.CreateDirectory(DocLocation);

            DocLocation += "MyCards.mmodb";

            ADOX.Catalog CreateDB = new ADOX.Catalog();
            CreateDB.Create("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + DocLocation + "; Jet OLEDB:Engine Type=5");

            ADOX.Table CardTable = new ADOX.Table();
            CardTable.Name = "MyCards";
            CardTable.Columns.Append("MultiverseID");
            CardTable.Columns.Append("Name");
            CardTable.Columns.Append("Expansion");
            CardTable.Columns.Append("stdAmount");
            CardTable.Columns.Append("foilAmount");
            CreateDB.Tables.Append(CardTable);

            OleDbConnection DBcon = CreateDB.ActiveConnection as OleDbConnection;
            if (DBcon != null)
                DBcon.Close();

            Marshal.ReleaseComObject(CreateDB.ActiveConnection);
            Marshal.ReleaseComObject(CreateDB);
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Properties.Settings.Default.OwnedDatabase = DocLocation;
            Properties.Settings.Default.Save();
        }
Exemplo n.º 2
1
public bool CreateNewAccessDatabase(string fileName)
        {
            bool result = false;

            ADOX.Catalog cat = new ADOX.Catalog();
            ADOX.Table table = new ADOX.Table();

            //Create the table and it's fields. 
            table.Name = "Table1";
            table.Columns.Append("Field1");
            table.Columns.Append("Field2");

            try
            {
                cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5");
                cat.Tables.Append(table);

                //Now Close the database
                ADODB.Connection con = cat.ActiveConnection as ADODB.Connection;
                if (con != null)
                    con.Close();

                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            cat = null;
            return result;
        }
Exemplo n.º 3
0
        /// <summary>
        /// Створення файла БД
        /// </summary>
        /// <param name="name">назва/шлях для файлу БД</param>
        /// <returns></returns>
        public static string CreateFile(string name)
        {
            // створення каталогу
            var catalog = new ADOX.Catalog();
            // провайдер і шлях до файлу БД
            string connect = "Provider=Microsoft.Jet." +
                             $@"OLEDB.4.0; Data Source = {name}.mdb";

            try
            {
                // створення бази данних
                catalog.Create(connect);
                Console.WriteLine("File of data base was create.");
            }
            catch (COMException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                catalog = null;
            }

            return(connect);
        }
        public string CreateDataBase(string CID, string CType)
        {
            connect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=BadgesTable.accdb;";
            string IsDataBaseCreated = connect.ConnectionString;

            if ((File.Exists("BadgesTable.accdb")))//update database
            {
                Console.WriteLine("Found");
                connect.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection  = connect;
                command.CommandText = "INSERT INTO Table1 (Badge_Number, Door_Access) values('" + CID + "','" + CType + "')";

                connect.Close();
            }
            else if (!(File.Exists("BadgesTable.accdb")))//Create the database.
            {
                var create = new ADOX.Catalog();
                create.Create(connect.ConnectionString);
                connect.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection  = connect;
                command.CommandText = "CREATE TABLE Table1 (" +
                                      "[Badge_Number] VARCHAR( 50 ) ," +
                                      "[Door_Access] VARCHAR( 50 ))";
                command.ExecuteNonQuery();
                command.CommandText = "INSERT INTO Table1 (Badge_Number, Door_Access) values('" + CID + "','" + CType + "')";
                command.ExecuteNonQuery();
                connect.Close();
            }
            return(IsDataBaseCreated);
        }
Exemplo n.º 5
0
        public static void CreateFile(string fileName, string pwd = "")
        {
            string dir = Path.GetDirectoryName(fileName);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            if (!File.Exists(fileName))
            {
                ADOX.Catalog cat = new ADOX.Catalog();
                cat.Create(Provider + @"Data Source=" + fileName + ";" + Password + "=" + pwd);

                ADODB.Connection con = cat.ActiveConnection as ADODB.Connection;
                if (con != null)
                {
                    con.Close();
                }
                cat.ActiveConnection = null;

                Marshal.ReleaseComObject(cat);
                cat = null;

                GC.Collect();
            }
        }
Exemplo n.º 6
0
        private void Form1_Load(object sender, EventArgs e)
        {
            OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder()
            {
                Provider   = "Microsoft.Jet.OLEDB.4.0",
                DataSource = System.IO.Directory.GetCurrentDirectory() + "\\database.accdb",
            };

            builder.Add("Jet OLEDB:Engine Type", 5);
            var catalog = new ADOX.Catalog();
            var table   = new ADOX.Table();

            table.Name = "DataTableSample1";
            table.Columns.Append("Column");
            table.Columns.Append("Column1");
            table.Columns.Append("Column2");
            if (!System.IO.File.Exists(builder.DataSource))
            {
                catalog.Create(builder.ConnectionString);
            }
            try {
                catalog.Tables.Append(table);
            } catch (Exception ex)
            {
                MessageBox.Show("Exists");
            }
            var connection = catalog.ActiveConnection as ADODB.Connection;

            if (connection != null)
            {
                connection.Close();
            }
        }
        /// <summary>
        /// This function will create the database that will be used for retreiving the PRPO data.
        /// </summary>
        /// <exception cref="DatabaseCreationFailureException"></exception>
        /// <returns>
        /// A boolean value indicating whether or not he database was created.
        /// </returns>
        public static bool CreateAccessDB()
        {
            bool result = false;

            ADOX.Catalog cat = new ADOX.Catalog();

            if (!File.Exists(AI.Path))
            {
                try
                {
                    cat.Create(AI.connectionString());
                    ADODB.Connection con = cat.ActiveConnection as ADODB.Connection;
                    if (con != null)
                    {
                        con.Close();
                    }
                    result = true;
                    AccessDatabaseUtils.US_PRPO_TableExists = false;
                    AccessDatabaseUtils.MX_PRPO_TableExists = false;
                }
                catch (Exception)
                {
                    throw new DatabaseCreationFailureException("There was an error while creating the MS Access Database.");
                }
            }
            return(result);
        }
Exemplo n.º 8
0
        public string CreateDataBase(string CID, string CType, string CDescription, string CAmount, string CdateIncident)
        {
            connect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CafeTable.accdb;";
            string IsDataBaseCreated = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CafeTable.accdb;";

            if ((File.Exists("CafeTable.accdb")))//update database
            {
                connect.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection  = connect;
                command.CommandText = "INSERT INTO Table1 (Meal_Number, Meal_Name, Meal_Description, Meal_Ingredients, Meal_Price) values('" + CID + "','" + CType + "','" + CDescription + "','" + CAmount + "','" + CdateIncident + "')"; command.ExecuteNonQuery();
                connect.Close();
            }
            else //Create the database.
            {
                var create = new ADOX.Catalog();
                create.Create(connect.ConnectionString);
                connect.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection  = connect;
                command.CommandText = "CREATE TABLE Table1 (" +
                                      "[Meal_Number] VARCHAR( 50 ) ," +
                                      "[Meal_Name] VARCHAR( 50 ) ," +
                                      "[Meal_Description] VARCHAR( 50 )," +
                                      "[Meal_Ingredients] VARCHAR( 50 )," +
                                      "[Meal_Price] VARCHAR( 50 ))";
                command.ExecuteNonQuery();
                command.CommandText = "INSERT INTO Table1 (Meal_Number, Meal_Name, Meal_Description, Meal_Ingredients, Meal_Price) values('" + CID + "','" + CType + "','" + CDescription + "','" + CAmount + "','" + CdateIncident + "')";
                command.ExecuteNonQuery();
                connect.Close();
            }
            return(IsDataBaseCreated);
        }
Exemplo n.º 9
0
 /// <summary>
 /// creates a new connection to an MS Access database and automatically
 /// opens the connection.
 /// </summary>
 /// <param name="connectionString"></param>
 public OleDBDataAccessLayer(string fileName)
     : base(string.Format("Provider=Microsoft.Jet.OleDb.4.0;Data Source={0}", fileName))
 {
     if (!System.IO.File.Exists(fileName))
     {
         ADOX.Catalog cat = new ADOX.Catalog();
         cat.Create(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Jet OLEDB:Engine Type=5", fileName));
     }
 }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            string myConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data source=C:\__tmp\myDB.accdb;";

            // the following code requires a COM reference to "Microsoft ADO Ext. 2.8 for DDL and Security"
            var cat = new ADOX.Catalog();

            cat.Create(myConnectionString);      // create a new, empty .accdb file

            Console.WriteLine("Done.");
        }
Exemplo n.º 11
0
 // 通过ADOX创建ACCESS数据库文件
 public static void CreatDataBase(string filename)
 {
     if (System.IO.File.Exists(filename))
     {
         System.IO.File.Delete(filename);
     }
     ADOX.Catalog cat = new ADOX.Catalog();
     cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";");
     System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.ActiveConnection);
     System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat);
 }
Exemplo n.º 12
0
 // 通过ADOX创建ACCESS数据库文件
 public static void CreatDataBase(string filename)
 {
     if (System.IO.File.Exists(filename))
     {
         System.IO.File.Delete(filename);
     }
     ADOX.Catalog cat = new ADOX.Catalog();
     cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";");
     System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.ActiveConnection);
     System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat);
 }
        private static void EnsureMdbExists(string dbFileName, string connectionString)
        {
            if (File.Exists(dbFileName))
            {
                return;
            }

            var catalog = new ADOX.Catalog();

            catalog.Create(connectionString);
        }
        static void Main(string[] args)
        {
            if (!((Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Utilities"))))
            {
                Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Utilities");
            }
            if (!(File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Utilities\\Veicoli.accdb")))
            {
                var cat = new ADOX.Catalog();
                cat.Create(connStr);
            }

            char scelta;

            do
            {
                menu();
                Console.Write("Scegli un'operazione da eseguire: ");
                scelta = Console.ReadKey().KeyChar;
                switch (scelta)
                {
                case '1':
                {
                    creaTabella();
                    break;
                }

                case '2':
                {
                    visualizzaListaVeicoli();
                    break;
                }

                case '3':
                {
                    Utils.esportaInWord();
                    break;
                }

                case '4':
                {
                    cancellaRecords();
                    break;
                }

                case '5':
                {
                    cancellaTabellaVeicoli();
                    break;
                }
                }
            }while (scelta != 'X' && scelta != 'x');
        }
Exemplo n.º 15
0
        public static OleDbConnection CreateOrOpenUserDataBase(string username)
        {
            ADOX.Catalog catalog = new ADOX.Catalog();

            OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();

            builder.DataSource = appDataPath + username + ".mdb";
            builder.Provider   = "Microsoft.Jet.OLEDB.4.0";
            myCon = new OleDbConnection();
            dbSet = new DataSet();
            try
            {
                myCon.ConnectionString = builder.ConnectionString;
                myCon.Open();
            }
            catch (Exception)
            {
                catalog.Create(builder.ConnectionString);
                CreateUserDatabase(catalog);
                myCon.ConnectionString = builder.ConnectionString;
                myCon.Open();
            }
            adapterMessage = new OleDbDataAdapter("select * from Message", myCon);
            adapterMessage.Fill(dbSet, "Message");
            adapterMessage.InsertCommand = new OleDbCommand("insert into [Message]([sender], [receiver], [content], [group_message], [type], [message_date]) Values(@sender, @receiver, @content, @group_message, @type, @message_date);", myCon);
            adapterMessage.InsertCommand.Parameters.Add(new OleDbParameter("@sender", OleDbType.WChar, 50, "sender"));
            adapterMessage.InsertCommand.Parameters.Add(new OleDbParameter("@receiver", OleDbType.WChar, 50, "receiver"));
            OleDbParameter tempPar = new OleDbParameter("@content", OleDbType.LongVarWChar);

            tempPar.SourceColumn = "content";
            adapterMessage.InsertCommand.Parameters.Add(tempPar);
            tempPar = new OleDbParameter("@group_Message", OleDbType.Boolean);
            tempPar.SourceColumn = "group_Message";
            adapterMessage.InsertCommand.Parameters.Add(tempPar);
            adapterMessage.InsertCommand.Parameters.Add(new OleDbParameter("@type", OleDbType.WChar, 50, "type"));
            tempPar = new OleDbParameter("@message_date", OleDbType.Date);
            tempPar.SourceColumn = "message_date";
            adapterMessage.InsertCommand.Parameters.Add(tempPar);
            adapterMessage.AcceptChangesDuringUpdate = true;


            adapterFriendRequest = new OleDbDataAdapter("select * from Friend_Request", myCon);
            adapterFriendRequest.Fill(dbSet, "Friend_Request");
            adapterFriendRequest.InsertCommand = new OleDbCommand("insert into Friend_Request(sender, receiver, request_date) values(@sender, @receiver, @request_date); ", myCon);
            adapterFriendRequest.InsertCommand.Parameters.Add(new OleDbParameter("@sender", OleDbType.WChar, 50, "sender"));
            adapterFriendRequest.InsertCommand.Parameters.Add(new OleDbParameter("@receiver", OleDbType.WChar, 50, "receiver"));
            tempPar = new OleDbParameter("@request_date", OleDbType.Date);
            tempPar.SourceColumn = "request_date";
            adapterFriendRequest.InsertCommand.Parameters.Add(tempPar);
            adapterFriendRequest.AcceptChangesDuringUpdate = true;

            return(myCon);
        }
Exemplo n.º 16
0
        private void ConvertSingleFile(string xlsFile, string mdbFile)
        {
            if (!File.Exists(xlsFile))
            {
                "Source file not existed".Notify();
                return;
            }

            string connStr =
                String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", xlsFile);

            if (!File.Exists(mdbFile))
            {
                string       createMDBFileString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbFile;
                ADOX.Catalog category            = new ADOX.Catalog();
                category.Create(createMDBFileString);

                /*here is the old way to create by offfice com */
                //Microsoft.Office.Interop.Access.ApplicationClass a = new Microsoft.Office.Interop.Access.ApplicationClass();
                //a.NewCurrentDatabase(mdbFile);
            }

            CoreEA.ICoreEAHander excelEg = new CoreEA.CoreE(CoreEA.CoreE.UsedDatabaseType.OleDb).X_Handler;

            excelEg.Open(new CoreEA.LoginInfo.LoginInfo_Oledb()
            {
                Database = xlsFile,
            });
            if (!excelEg.IsOpened)
            {
                "Can't open excel file.the action will cancel".Notify();
                return;
            }

            OleDbConnection conn = new OleDbConnection(connStr);
            OleDbCommand    cmd  = new OleDbCommand();

            cmd.Connection = conn;
            conn.Open();
            string cmdText = string.Empty;

            foreach (string item in excelEg.GetTableListInDatabase())
            {
                cmdText =
                    String.Format("SELECT * INTO [MS Access;Database={0}].[{1}] FROM [{2}]", mdbFile, item, item);
                cmd.CommandText = cmdText;
                cmd.ExecuteNonQuery();
            }


            conn.Close();
        }
Exemplo n.º 17
0
        private bool CreateNewFile(string connectionString)
        {
            if (File.Exists(this.FileName))
            {
                return(false);
            }

            // create access database file with the ADO-ActiveX
            ADOX.Catalog catalog = new ADOX.Catalog();
            catalog.Create(connectionString);
            catalog.ActiveConnection.Close();
            return(true);
        }
Exemplo n.º 18
0
 private void button2_Click(object sender, EventArgs e)
 {
     if (!File.Exists("Config"))
     {
         MessageBox.Show("設定檔不存在!!請載入設定用EXCEL");
     }
     if (ChapterNunber == 0)
     {
         MessageBox.Show("未選擇章節");
     }
     else if (Catagory == 0)
     {
         MessageBox.Show("未選擇測試種類");
     }
     else if (ChapterNunber == 0 && Catagory == 0)
     {
         MessageBox.Show("兩者皆未選擇");
     }
     else if (Catagory == 1)
     {
         static_test(ChapterNunber);
     }
     else if (Catagory == 2)
     {
         dynamic_test(ChapterNunber);
     }
     else if (Catagory == 3)
     {
         if (!File.Exists("Config"))
         {
             MessageBox.Show("設定檔不存在!!");
             return;
         }
         if (!File.Exists("board.accdb"))
         {
             ADOX.Catalog cat = new ADOX.Catalog();
             cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=board.accdb;");
             cat.ActiveConnection.Close();
         }
         else
         {
             File.Delete("board.accdb");
             ADOX.Catalog cat = new ADOX.Catalog();
             cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=board.accdb;");
             cat.ActiveConnection.Close();
         }
         DataBaseProcess baseProcess = new DataBaseProcess(DeserializeBinary(), path);
         MessageBox.Show("Done");
     }
 }
Exemplo n.º 19
0
 /// <summary>
 /// 创建 Access 数据库
 /// </summary>
 /// <param name="path">数据库路径</param>
 /// <param name="password">密码</param>
 /// <returns></returns>
 static string createDatabaseForAccess(DBConnection connection)
 {
     try
     {
         IOUtil.createDirectoryIfNotExist(IOUtil.directoryPath(connection.server_name));
         var          path              = connection.server_name.Replace(AppDomain.CurrentDomain.BaseDirectory, "");
         ADOX.Catalog cc                = new ADOX.Catalog();
         var          psw_part          = connection.password.hasContents() ? $"Jet OLEDB:Database Password={connection.password};" : "";
         var          initialize_string = $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={path};{psw_part}Jet OLEDB:Engine Type=5";
         cc.Create(initialize_string);
         cc = null;
         return("");
     }
     catch (Exception ex) { return(ex.Message); }
 }
Exemplo n.º 20
0
        private void button1_Click(object sender, EventArgs e)
        {
            var Каталог = new ADOX.Catalog();

            try
            {
                Каталог.Create("Provider=Microsoft.Jet." +
                               "OLEDB.4.0;Data Source=new_BD.mdb");
                MessageBox.Show("База успешно создана");
            }
            catch (System.Runtime.InteropServices.COMException Ситуация)
            {
                MessageBox.Show(Ситуация.Message);
            }
        }
Exemplo n.º 21
0
        private static void CreateAccessDatabase(string connectionString)
        {
            var db = new ADOX.Catalog();
            db.Create(connectionString);
            db.Tables.Append(_logFileProcessor.GetTable());

            // get active connection if any
            var connection = db.ActiveConnection as ADODB.Connection;

            // close connection to database if open
            if (connection != null) connection.Close();

            // release memory
            db = null;
        }
Exemplo n.º 22
0
        public static void SaveToAccess(DataTable temp, string path)
        {
            OleDbConnection connection;
            string          tableName = temp.TableName;

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            {
                ADOX.Catalog catalog      = new ADOX.Catalog();
                var          createMdbStr = $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={path};Jet OLEDB:Engine Type=5";
                catalog.Create(createMdbStr);
                connection = new OleDbConnection($"Provider=Microsoft.Jet.OLEDB.4.0;Data source={path};Persist Security Info=False;Jet OLEDB:Database Password="******"CREATE TABLE {tableName}(序号 int IDENTITY(1, 1) PRIMARY KEY not null,时间 char({dateFormat.Length}),方向 char(8),地址 char(8),数据 char(23))", connection);
                try { cmd.ExecuteNonQuery(); }
                catch (Exception)
                {
                }
            }
            try
            {
                OleDbDataAdapter    adapter = new OleDbDataAdapter($"SELECT * FROM {tableName}", connection); //建立一个DataAdapter对象
                OleDbCommandBuilder cb      = new OleDbCommandBuilder(adapter);                               //这里的CommandBuilder对象一定不要忘了,一般就是写在DataAdapter定义的后面
                cb.QuotePrefix = "[";
                cb.QuoteSuffix = "]";
                DataSet ds = new DataSet();  //建立DataSet对象
                adapter.Fill(ds, tableName); //填充DataSet
                var dsTable = ds.Tables[tableName];
                foreach (DataRow tempRow in temp.Rows)
                {
                    DataRow dr = dsTable.NewRow();
                    dr.ItemArray = tempRow.ItemArray;//行复制
                    dsTable.Rows.Add(dr);
                }
                adapter.Update(ds, tableName);//用DataAdapter的Update()方法进行数据库的更新
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                connection.Close();
            }
        }
Exemplo n.º 23
0
        private void AbrirMDB()
        {
            txtArquivo.Enabled = false;
            button1.Enabled    = false;
            DBPath             = Application.StartupPath + "\\Arquivos\\" + lblOcultoArquivo.Text;

            // create DB via ADOX if not exists
            if (!File.Exists(DBPath))
            {
                ADOX.Catalog cat = new ADOX.Catalog();
                cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DBPath);
                cat = null;
            }

            // connect to DB
            conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DBPath);
            conn.Open();

            // create table "Table_1" if not exists
            // DO NOT USE SPACES IN TABLE AND COLUMNS NAMES TO PREVENT TROUBLES WITH SAVING, USE _
            // OLEDBCOMMANDBUILDER DON'T SUPPORT COLUMNS NAMES WITH SPACES
            try
            {
                using (OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Table_1] ([id] COUNTER PRIMARY KEY, [text_column] MEMO, [int_column] INT);", conn))
                {
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex) { if (ex != null)
                                   {
                                       ex = null;
                                   }
            }

            // get all tables from DB
            using (DataTable dt = conn.GetSchema("Tables"))
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i].ItemArray[dt.Columns.IndexOf("TABLE_TYPE")].ToString() == "TABLE")
                    {
                        comboBoxTables.Items.Add(dt.Rows[i].ItemArray[dt.Columns.IndexOf("TABLE_NAME")].ToString());
                    }
                }
            }
        }
Exemplo n.º 24
0
        public static void add()
        {
            var k = new ADOX.Catalog();

            try
            {
                k.Create("Provider= Microsoft.Jet.OLEDB.4.0;Data Source = C:\\Users\\three\\Desktop\\ТехнологияПрограммирования\\ТехнологияПрограммирования\\mas1.mdb");
                MessageBox.Show("БД успешно создана");
            }
            catch (System.Runtime.InteropServices.COMException sit)
            {
                MessageBox.Show(sit.Message);
            }
            finally
            {
                k = null;
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// 创建数据库文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="tableName"></param>
        public void CreateAccDB(string fileName, string tableName)
        {
            try
            {
                if (System.IO.File.Exists(fileName))
                {
                    return;
                }
                ADOX.Catalog cat = new ADOX.Catalog();
                cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName);

                acTable.CreateColumns(cat, tableName);
                cat = null;
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 26
0
        /* Методы для работы с БД */

        // Создание БД
        public static void createDB()
        {
            var db = new ADOX.Catalog();

            try
            {
                db.Create(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='..\Massiv.accdb';");
                MessageBox.Show("БД успешно создана");
            }
            catch (System.Runtime.InteropServices.COMException sit)
            {
                MessageBox.Show(sit.Message);
            }
            finally
            {
                db = null;
            }
        }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            ADOX.Catalog catalog = new ADOX.Catalog();

            try
            {
                catalog.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=e:\\new_DB.mdb");

                MessageBox.Show("База данных Е:\\new_DB.mdb успешно создана");
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                catalog = null;
            }
        }
Exemplo n.º 28
0
        public static void UpdateAccess(DataTable temp, string path)
        {
            string tableName = Path.GetFileNameWithoutExtension(path);

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            {
                ADOX.Catalog catalog      = new ADOX.Catalog();
                var          createMdbStr = $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={path};Jet OLEDB:Engine Type=5";
                catalog.Create(createMdbStr);
                CreateTable(tableName, path);
            }
            OleDbConnection con = new OleDbConnection($"Provider=Microsoft.Jet.OLEDB.4.0;Data source={path};Persist Security Info=False;Jet OLEDB:Database Password="******"SELECT * FROM {tableName}", con); //建立一个DataAdapter对象

                OleDbCommandBuilder cb = new OleDbCommandBuilder(adapter);                          //这里的CommandBuilder对象一定不要忘了,一般就是写在DataAdapter定义的后面
                cb.QuotePrefix = "[";
                cb.QuoteSuffix = "]";
                DataSet ds = new DataSet();  //建立DataSet对象
                adapter.Fill(ds, tableName); //填充DataSet
                foreach (DataRow tempRow in temp.Rows)
                {
                    DataRow dr = ds.Tables[tableName].NewRow();
                    dr.ItemArray = tempRow.ItemArray;//行复制
                    ds.Tables[tableName].Rows.Add(dr);
                }
                adapter.Update(ds, tableName);//用DataAdapter的Update()方法进行数据库的更新
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                con.Close();
            }
        }
Exemplo n.º 29
0
        private static void CreateAccessDatabase(string connectionString)
        {
            var db = new ADOX.Catalog();

            db.Create(connectionString);
            db.Tables.Append(_logFileProcessor.GetTable());

            // get active connection if any
            var connection = db.ActiveConnection as ADODB.Connection;

            // close connection to database if open
            if (connection != null)
            {
                connection.Close();
            }

            // release memory
            db = null;
        }
Exemplo n.º 30
0
        private static void CreateBase(Base b, String path)
        {
            String udl = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
                         + path
                         + ";Mode=ReadWrite;Persist Security Info=False";

            ADOX.Catalog cat = new ADOX.Catalog();

            cat.Create(
                "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
                + path
                );
            b.conn = new System.Data.OleDb.OleDbConnection(udl);
            b.conn.Open();
            System.Data.OleDb.OleDbCommand com = b.conn.CreateCommand();
            com.CommandText = "create table Common(Path VARCHAR(255))";

            com.ExecuteNonQuery();
        }
Exemplo n.º 31
0
 private void Form1_Load(object sender, EventArgs e)
 {
     if (File.Exists("DatabaseCS.accdb") == false)//If the database doesn't exist
     {
         ADOX.Catalog cat = new ADOX.Catalog();
         cat.Create(Program.ConnString); //Use constant defined in Program.cs to create database
         OleDbConnection Conn = new OleDbConnection(Program.ConnString);
         Conn.Open();
         OleDbCommand Cmd = new OleDbCommand();
         Cmd.Connection = Conn;
         //Create Classes Users - The CREATE command needs to be constructed as one string.
         Cmd.CommandText  = "CREATE TABLE Users(Username VARCHAR(10),";
         Cmd.CommandText += " PWord VARCHAR(15), PRIMARY KEY (Username))";
         Cmd.ExecuteNonQuery(); //Used because no result is returned
         Cmd.CommandText = "INSERT INTO Users VALUES('Adm1n','Pas$w0rd')";
         Cmd.ExecuteNonQuery();
         //Create the Borrowers table
         Cmd.CommandText  = "CREATE TABLE Borrowers(BorrowerNumber CHAR(14),";
         Cmd.CommandText += " Firstname VARCHAR(25), Surname VARCHAR(20),";
         Cmd.CommandText += " DateOfBirth DATE, Sex VARCHAR(6),";
         Cmd.CommandText += " Address VARCHAR(40), EmailAddress VARCHAR(25), ContactNumber CHAR(11),";
         Cmd.CommandText += " BorrowerCategory VARCHAR(20), Branch VARCHAR(15),";
         Cmd.CommandText += " PRIMARY KEY (BorrowerNumber))";
         Cmd.ExecuteNonQuery();
         //Create the Items table
         Cmd.CommandText  = "CREATE TABLE Items(ItemBarcode CHAR(14), Title VARCHAR(50),";
         Cmd.CommandText += " Author VARCHAR(45), Price MONEY, Collection VARCHAR(30), ItemLocation VARCHAR(20),";
         Cmd.CommandText += " PRIMARY KEY(ItemBarcode))";
         Cmd.ExecuteNonQuery();
         //Create the Loans table
         Cmd.CommandText  = "CREATE TABLE Loans(LoanCode CHAR(14), BorrowerNumber CHAR(14), ItemBarcode CHAR(14),";
         Cmd.CommandText += " Issued DATE, LoanPolicy VARCHAR(25), LoanDue DATE,";
         Cmd.CommandText += " Complete VARCHAR(20), Primary Key(LoanCode),";
         Cmd.CommandText += " FOREIGN KEY(BorrowerNumber) REFERENCES Borrowers(BorrowerNumber),";
         Cmd.CommandText += " FOREIGN KEY(ItemBarcode) REFERENCES Items(ItemBarcode))";
         Cmd.ExecuteNonQuery();
         Conn.Close();
     }
     //causes whatever is entered as the password to be displayed as asterisks
     tbPassword.Text         = "";
     tbPassword.PasswordChar = '*';
 }
Exemplo n.º 32
0
        public DbCreator()
        {
            //Создаем новую базу в конструкторе
            StartOfDbCreator:
            try
            {
                ADOX.Catalog BD = new ADOX.Catalog();
                BD.Create(connectionString);
                BD = null;
            }
            catch (Exception ex)
            {
                if (ex.Message == "База данных уже существует.")
                {
                    MessageForm form = new MessageForm();
                    form.ShowDialog();
                    if (rewriteVar == 1)
                    {
                        try { File.Delete(filePath); }
                        catch (Exception e)
                        {
                            MessageBox.Show("Error: Failed to rewrite a database." + e.Message);

                        }
                        rewriteVar = 0;
                        goto StartOfDbCreator;
                    }
                    else if (rewriteVar == 2)
                    {
                        rewriteVar = 0;
                        goto StartOfDbCreator;
                    }
                }
                else
                    MessageBox.Show("Error: Failed to create a database." + ex.Message);
                return;
            }

            //Создаем пустую таблицу и добавляем ее в базу
            DataTable myDataTable = new DataTable();
            dbModification(connectionString, clearCreation, myDataTable, false);
        }
Exemplo n.º 33
0
 /// <summary>
 /// 建立数据库连接.
 /// </summary>
 /// <returns></returns>
 public string ConnectMdb(string dbPath)
 {
     try
     {
         ADOX.Catalog cataLog = new ADOX.Catalog();
         bool         a       = File.Exists(dbPath);
         if (!File.Exists(dbPath))
         {
             cataLog.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dbPath + ";" + "Jet OLEDB:Engine Type=5");
         }
         string accConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + dbPath;
         accConn = new OleDbConnection(accConnStr);
         accConn.Open();
         ShowTableNames(combox_table_names);
     }
     catch (Exception ex)
     {
         return(ex.Message + "  -->ConnectMdb");
     }
     return("OK");
 }
Exemplo n.º 34
0
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                ADOX.Catalog cat = new ADOX.Catalog();
                //ADOX.CatalogClass cat = new ADOX.CatalogClass();
                string archivo = textBox3.Text;
                string cusu    = textBox4.Text;
                cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" +
                           "Data Source=" + cusu + "\\" + archivo + ".mdb;" +
                           "Jet OLEDB:Engine Type=5");

                MessageBox.Show("Database Created Successfully");

                cat = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Se ha producido un error" + ex);
            }
        }
Exemplo n.º 35
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (comboBox1.Text.ToString() == "")
            {
                MessageBox.Show("Выбери год", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (comboBox2.Text.ToString() == "")
            {
                MessageBox.Show("Выбери месяц", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (textBox1.Text == "")
            {
                MessageBox.Show("Выбери файл", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                string strConn;
                //Check for Excel version
                if (textBox1.Text.Substring(textBox1.Text.LastIndexOf('.')).ToLower() == ".xlsx")
                {
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox1.Text + ";Extended Properties=\"Excel 12.0;HDR=YES; IMEX=0\"";
                }
                else
                {
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR=YES; IMEX=0\"";
                }

                System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection(strConn);
                con.Open();
                DataSet ds = new DataSet();
                DataTable shemaTable = con.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,
                    new object[] { null, null, null, "TABLE" });
                string sheet1 = (string)shemaTable.Rows[0].ItemArray[2];
                string select = String.Format("SELECT * FROM [{0}]", sheet1);
                System.Data.OleDb.OleDbDataAdapter ad = new System.Data.OleDb.OleDbDataAdapter(select, con);
                ad.Fill(ds);
                if (System.IO.File.Exists("your_base.mdb"))
                {
                    int year = Convert.ToInt32(comboBox1.Text.ToString());
                    int month = Convert.ToInt32(comboBox2.Text.ToString());
                    string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your_base.mdb;Jet OLEDB:Engine Type=5";
                    System.Data.OleDb.OleDbConnection connectDb = new System.Data.OleDb.OleDbConnection(conStr);
                    connectDb.Open();
                    System.Data.OleDb.OleDbCommand myCMD = new System.Data.OleDb.OleDbCommand();
                    myCMD.Connection = connectDb;
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        myCMD.CommandText = "Insert into SURVEY (Anim, weight, height, s_year, s_month) VALUES (\"" +
                            ds.Tables[0].Rows[i][0] + "\", " + ds.Tables[0].Rows[i][1] + ", " + ds.Tables[0].Rows[i][2] + ", " + year + ", " + month + ")";
                        myCMD.ExecuteNonQuery();
                    }
                    MessageBox.Show("Данные загружены в БД", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    int year = Convert.ToInt32(comboBox1.Text.ToString());
                    int month = Convert.ToInt32(comboBox2.Text.ToString());
                    ADOX.Catalog cat = new ADOX.Catalog();
                    string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5";
                    cat.Create(String.Format(connstr, "your_base.mdb"));
                    cat = null;
                    string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your_base.mdb;Jet OLEDB:Engine Type=5";
                    Querry("CREATE TABLE SURVEY(Anim varchar(255), weight int, height int, s_year int, s_month int);", "your_base.mdb");
                    System.Data.OleDb.OleDbConnection connectDb = new System.Data.OleDb.OleDbConnection(conStr);
                    connectDb.Open();
                    System.Data.OleDb.OleDbCommand myCMD = new System.Data.OleDb.OleDbCommand();
                    myCMD.Connection = connectDb;
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        myCMD.CommandText = "Insert into SURVEY (Anim, weight, height, s_year, s_month) VALUES (\"" +
                            ds.Tables[0].Rows[i][0] + "\", " + ds.Tables[0].Rows[i][1] + ", " + ds.Tables[0].Rows[i][2] + ", " + year + ", " + month + ")";
                        myCMD.ExecuteNonQuery();
                    }
                    //string comm = "Insert into SURVEY (Anim, weight, height) VALUES (hare, 10, 20)";
                    //System.Data.OleDb.OleDbDataAdapter dbAdp = new System.Data.OleDb.OleDbDataAdapter(comm, conStr);
                    //dbAdp.Update(ds.Tables[0]);
                    MessageBox.Show("Данные загружены в БД", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                con.Close();

            }
        }
Exemplo n.º 36
0
        public static void AssemblyInit()
        {
            File.Delete(databaseFileName);


            var connectionString = ConfigurationManager.ConnectionStrings["AccessTestDatabase"].ConnectionString;

            var cat = new ADOX.Catalog();
            cat.Create(connectionString);

            var dbConnection = new OleDbConnection(connectionString);

            using (dbConnection)
            {
                dbConnection.Open();


                string sql = @"
CREATE TABLE Employee
(
	EmployeeKey COUNTER PRIMARY KEY,
	FirstName TEXT(30) NOT NULL,
	MiddleName TEXT(30) NULL,
	LastName TEXT(30) NOT NULL,
	Title TEXT(100) null,
	ManagerKey LONG NULL REFERENCES Employee(EmployeeKey),
    CreatedDate DateTime NOT NULL DEFAULT NOW(),
    UpdatedDate DateTime NULL
)";

                string sql2 = @"CREATE TABLE Customer
(
	CustomerKey COUNTER PRIMARY KEY, 
    FullName TEXT(100) NULL,
	State TEXT(2) NOT NULL,
    CreatedByKey INTEGER NULL,
    UpdatedByKey INTEGER NULL,
	CreatedDate DATETIME NULL DEFAULT NOW(),
    UpdatedDate DATETIME NULL,
	DeletedFlag BIT NOT NULL DEFAULT 0,
	DeletedDate DateTime NULL,
	DeletedByKey INTEGER NULL
)";

                string sql3 = @"CREATE VIEW EmployeeLookup AS SELECT FirstName, LastName, EmployeeKey FROM Employee";

                using (var command = new OleDbCommand(sql, dbConnection))
                    command.ExecuteNonQuery();

                using (var command = new OleDbCommand(sql2, dbConnection))
                    command.ExecuteNonQuery();

                using (var command = new OleDbCommand(sql3, dbConnection))
                    command.ExecuteNonQuery();

                sql = @"INSERT INTO Employee ([FirstName], [MiddleName], [LastName], [Title], [ManagerKey]) VALUES (@FirstName, @MiddleName, @LastName, @Title, @ManagerKey)";

                sql2 = @"INSERT INTO Employee ([FirstName], [MiddleName], [LastName], [Title], [ManagerKey], [CreatedDate]) VALUES (@FirstName, @MiddleName, @LastName, @Title, @ManagerKey, @CreatedDate)";

                //Date/Time format - 4/30/2016 5:25:17 PM
                const string DateTimeFormat = "M/d/yyyy h:mm:ss tt";

                using (var command = new OleDbCommand(sql, dbConnection))
                {
                    //command.Parameters.AddWithValue("@EmployeeKey", DBNull.Value);
                    command.Parameters.AddWithValue("@FirstName", "Tom");
                    command.Parameters.AddWithValue("@MiddleName", DBNull.Value);
                    command.Parameters.AddWithValue("@LastName", "Jones");
                    command.Parameters.AddWithValue("@Title", "CEO");
                    command.Parameters.AddWithValue("@ManagerKey", DBNull.Value);
                    command.ExecuteNonQuery();
                }


                using (var command = new OleDbCommand(sql2, dbConnection))
                {
                    //command.Parameters.AddWithValue("@EmployeeKey", DBNull.Value);
                    command.Parameters.AddWithValue("@FirstName", "Tom");
                    command.Parameters.AddWithValue("@MiddleName", DBNull.Value);
                    command.Parameters.AddWithValue("@LastName", "Jones");
                    command.Parameters.AddWithValue("@Title", "CEO");
                    command.Parameters.AddWithValue("@ManagerKey", DBNull.Value);
                    command.Parameters.AddWithValue("@CreatedDate", DateTime.Now.ToString(DateTimeFormat));
                    command.ExecuteNonQuery();
                }


                using (var command = new OleDbCommand(sql2, dbConnection))
                {
                    //command.Parameters.AddWithValue("@EmployeeKey", DBNull.Value);
                    command.Parameters.AddWithValue("@FirstName", "Tom");
                    command.Parameters.AddWithValue("@MiddleName", DBNull.Value);
                    command.Parameters.AddWithValue("@LastName", "Jones");
                    command.Parameters.AddWithValue("@Title", "CEO");
                    command.Parameters.AddWithValue("@ManagerKey", DBNull.Value);
                    var param = command.Parameters.AddWithValue("@CreatedDate", DateTime.Now);
                    param.OleDbType = OleDbType.Date;
                    command.ExecuteNonQuery();
                }

                using (var command = new OleDbCommand("SELECT @@IDENTITY", dbConnection))
                {
                    var key = command.ExecuteScalar();

                    using (var command2 = new OleDbCommand("UPDATE Employee SET MiddleName = 'Frank' WHERE EmployeeKey = @EmployeeKey", dbConnection))
                    {
                        command2.Parameters.AddWithValue("@EmployeeKey", key);
                        var updateCount = command2.ExecuteNonQuery();

                    }
                }
            }

        }
Exemplo n.º 37
0
        /// <summary>
        /// Creates a new database and sets how many cards this is going to pull from Gatherer
        /// </summary>
        /// <returns></returns>
        static string mkDatabase()
        {
            try
            {
                Console.WriteLine("Enter the path/name for the new database. \nExample: C:\\Users\\w9jds\\Desktop\\GathererDB.mdb");
                string input = Console.ReadLine();

                do
                {
                    try
                    {
                        Console.WriteLine("What multiverseid would you like to start with?");
                        multiverseidstart = Convert.ToInt32(Console.ReadLine());
                        Console.WriteLine("What multiverseid would you like to end with?");
                        multiverseidend = Convert.ToInt32(Console.ReadLine());
                    }
                    catch (Exception) { multiverseidend = 0; multiverseidstart = 1; }
                } while (multiverseidstart > multiverseidend);

                ADOX.Catalog CreateDB = new ADOX.Catalog();

                ADOX.Table CardTable = new ADOX.Table();
                CardTable.Name = "Cards";
                CardTable.Columns.Append("MultiverseID");
                CardTable.Columns.Append("Name");
                CardTable.Columns.Append("ConvManaCost");
                CardTable.Columns.Append("Type");
                CardTable.Columns.Append("CardText");
                CardTable.Columns.Append("Power");
                CardTable.Columns.Append("Toughness");
                CardTable.Columns.Append("Expansion");
                CardTable.Columns.Append("Rarity");
                CardTable.Columns.Append("ImgURL");

                CreateDB.Create("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + input + "; Jet OLEDB:Engine Type=5");
                CreateDB.Tables.Append(CardTable);

                //ask: Console.WriteLine("Would you like to add card legalities to the database? (Will add A LOT of time to runtime.) y/n");
                //    string leginput = Console.ReadLine();
                //    if (string.Equals(leginput, "y", StringComparison.OrdinalIgnoreCase) == true || string.Equals(leginput, "yes", StringComparison.OrdinalIgnoreCase))
                //        incLegality = true;
                //    else if (string.Equals(leginput, "n", StringComparison.OrdinalIgnoreCase) == true || string.Equals(leginput, "no", StringComparison.OrdinalIgnoreCase))
                //        incLegality = false;
                //    else
                //        goto ask;

                //if (incLegality == true)
                //{
                //    ADOX.Table Legality = new ADOX.Table();
                //    Legality.Name = "CardsLegality";
                //    Legality.Columns.Append("MultiverseID");
                //    Legality.Columns.Append("Format");
                //    Legality.Columns.Append("Legality");
                //    CreateDB.Tables.Append(Legality);
                //}

                OleDbConnection DBcon = CreateDB.ActiveConnection as OleDbConnection;
                if (DBcon != null)
                    DBcon.Close();

                return input;
            }
            catch (OleDbException) { Console.WriteLine("Entered Invalid Path"); return null; }
            catch (Exception) { Console.WriteLine("\nAn error has occured while making the Database"); return null; }
        }
Exemplo n.º 38
0
        internal static Boolean CreateAccessDatabase(String DatabaseFullPath)
        {
            Boolean bAns = false;
              ADOX.Catalog cat = new ADOX.Catalog();

              try
              {
            string theConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DatabaseFullPath;

            cat.Create(theConnection);

            bAns = true;
              }
              catch (System.Runtime.InteropServices.COMException ex)
              {
            MessageBox.Show(ex.Message);
            bAns = false;
              }

              cat = null;

              return bAns;
        }
Exemplo n.º 39
0
        //private void Delete()
        //{
        //    Process proc = new Process();
        //    proc.StartInfo.CreateNoWindow = true;
        //    proc.StartInfo.FileName = "cmd.exe";
        //    proc.StartInfo.UseShellExecute = false;
        //    proc.StartInfo.RedirectStandardError = true;
        //    proc.StartInfo.RedirectStandardInput = true;
        //    proc.StartInfo.RedirectStandardOutput = true;
        //    proc.Start();
        //    proc.StandardInput.WriteLine("del " + m_strFilePathName.Substring(0, m_strFilePathName.Length - 3) + "ldb");
        //    proc.StandardInput.WriteLine("del " + m_strFilePathName);
        //    //proc.StandardInput.WriteLine("delete " + m_strPath + ".tmp.mdb");
        //    proc.Close();
        //}
        private bool Connect(string strFilePathName)
        {
            try
            {
                m_strFilePathName = strFilePathName;
                if (File.Exists(strFilePathName))
                {
                    try
                    {
                        File.Delete(strFilePathName);
                    }
                    catch (Exception ee)
                    {
                        //Delete();
                        strFilePathName += "_1.mdb";
                    }
                }

                try
                {
                    ADOX.Catalog catalog = new ADOX.Catalog();
                    catalog.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePathName + ";Jet OLEDB:Engine Type=5");
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(catalog.ActiveConnection);
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(catalog);
                }
                catch (Exception ee)
                {
                }

                DbConnectionStringBuilder dcsBuilder = new DbConnectionStringBuilder();

                dcsBuilder.Clear();
                dcsBuilder.Add("Provider", "Microsoft.Jet.Oledb.4.0");
                dcsBuilder.Add("User ID", "Admin");
                dcsBuilder.Add("Password", "");
                dcsBuilder.Add("Data Source", @strFilePathName);

                m_pOleDbConnection = new OleDbConnection(dcsBuilder.ConnectionString);

                m_pOleDbConnection.Open();

                //m_pPolygonNodeTable = new PolygonNodeTable(m_pOleDbConnection, true);
                //m_pLineNodeExTable = new LineNodeExTable(m_pOleDbConnection, true);
                //m_pLineNodeTable = new LineNodeTable(m_pOleDbConnection, true);

                return true;
            }
            catch (Exception ex)
            {
                Logger.WriteErrorLog(ex);
            }
            return false;
        }
Exemplo n.º 40
0
        /// <summary>
        /// Opens or creates an MS Access database file for writing
        /// </summary>
        public bool SetWriteFile(string filename)
        {
            _filename = filename;

            string connString = String.Format("Provider={0}; Data Source={1};", "Microsoft.Jet.OLEDB.4.0", _filename);
            if (!System.IO.File.Exists(filename))
            {
                ADOX.Catalog arghCatalog = new ADOX.Catalog();
                arghCatalog.Create(connString);
            }

            //if the file doesn't exist, do I need a different connection string?
            _conn = new System.Data.OleDb.OleDbConnection(connString);
            _conn.Open();

            if ((_conn == null) || (_conn.State != System.Data.ConnectionState.Open))
                return false;

            return true;
        }
Exemplo n.º 41
0
        public void ExportQueryToDB(DataSet ds)
        {
            try
            {
                //The connection strings needed: One for SQL and one for Access
                String accessConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\Report\\Report.mdb"; //"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\...\\test.accdb;";
                //String sqlConnectionString = "Data Source=LUKMAN\SQLEXPRESSR22008;Initial Catalog=Your_Catalog;Integrated Security=True";

                //Make adapters for each table we want to export
                //SqlDataAdapter adapter1 = new SqlDataAdapter("select * from Table1", sqlConnectionString);
                //SqlDataAdapter adapter2 = new SqlDataAdapter("select * from Table2", sqlConnectionString);

                ////Fills the data set with data from the SQL database
                //DataSet dataSet = new DataSet();
                //adapter1.Fill(dataSet, "Table1");
                //adapter2.Fill(dataSet, "Table2");
                if (File.Exists(Application.StartupPath + "\\Report\\Report.mdb"))
                {
                    //Create an empty Access file that we will fill with data from the data set
                    File.Delete(Application.StartupPath + "\\Report\\Report.mdb");
                }
                ADOX.Catalog catalog = new ADOX.Catalog();
                catalog.Create(accessConnectionString);
                //Create an Access connection and a command that we'll use
                OleDbConnection accessConnection = new OleDbConnection(accessConnectionString);
                OleDbCommand command = new OleDbCommand();
                command.Connection = accessConnection;
                command.CommandType = CommandType.Text;
                accessConnection.Open();

                //This loop creates the structure of the database
                foreach (DataTable table in ds.Tables)
                {
                    String columnsCommandText = "(";
                    foreach (DataColumn column in table.Columns)
                    {
                        String columnName = column.ColumnName;
                        String dataTypeName = column.DataType.Name == "Boolean" || column.DataType.Name == "Int32" || column.DataType.Name == "Int64" || column.DataType.Name == "Integer" ? "Number" : column.DataType.Name;
                        String sqlDataTypeName = dataTypeName;//getSqlDataTypeName(dataTypeName);
                        columnsCommandText += "[" + columnName + "] " + sqlDataTypeName + ",";
                        //columnsCommandText += "[" + columnName + "] "  + ",";
                    }
                    columnsCommandText = columnsCommandText.Remove(columnsCommandText.Length - 1);
                    columnsCommandText += ")";

                    command.CommandText = "CREATE TABLE " + table.TableName + columnsCommandText;

                    command.ExecuteNonQuery();
                }

                //This loop fills the database with all information
                foreach (DataTable table in ds.Tables)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        String commandText = "INSERT INTO " + table.TableName + " VALUES (";
                        foreach (var item in row.ItemArray)
                        {
                            commandText += "'" + item.ToString() + "',";
                        }
                        commandText = commandText.Remove(commandText.Length - 1);
                        commandText += ")";

                        command.CommandText = commandText;
                        command.ExecuteNonQuery();
                    }
                }

                accessConnection.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }