Situation: I am creating an automatic task that queries MySQL (via ODBC) and inserts the result into the MS Access database (.mdb) using OLEDB.
The code:
OleDbConnection accCon = new OleDbConnection(); OdbcCommand mySQLCon = new OdbcCommand(); try { //connect to mysql Connect(); mySQLCon.Connection = connection; //connect to access accCon.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data source= " + pathToAccess; accCon.Open(); var cnt = 0; while (cnt < 5) { if (accCon.State == ConnectionState.Open) break; cnt++; System.Threading.Thread.Sleep(50); } if (cnt == 5) { ToolBox.logThis("Connection to Access DB did not open. Exit Process"); return; } } catch (Exception e) { ToolBox.logThis("Faild to Open connections. msg -> " + e.Message + "\\n" + e.StackTrace); } OleDbCommand accCmn = new OleDbCommand(); accCmn.Connection = accCon; //access insert query structure var insertAccessQuery = "INSERT INTO {0} values({1});"; // key = > tbl name in access, value = > mysql query to b executed foreach (var table in tblNQuery) { try { mySQLCon.CommandText = table.Value; //executed mysql query using (var dataReader = mySQLCon.ExecuteReader()) { //variable to hold row data var rowData = new object[dataReader.FieldCount]; var parameters = ""; //read the result set from mysql query while (dataReader.Read()) { //fill rowData with the row values dataReader.GetValues(rowData); //build the parameters for insert query for (var i = 0; i < dataReader.FieldCount; i++) parameters += "'" + rowData[i] + "',"; parameters = parameters.TrimEnd(','); //insert to access accCmn.CommandText = string.Format(insertAccessQuery, table.Key, parameters); try { accCmn.ExecuteNonQuery(); } catch (Exception exc) { ToolBox.logThis("Faild to insert to access db. msg -> " + exc.Message + "\\n\\tInsert query -> " + accCmn.CommandText ); } parameters = ""; } } } catch (Exception e) { ToolBox.logThis("Faild to populate access db. msg -> " + e.Message + "\\n" + e.StackTrace); } } Disconnect(); accCmn.Dispose(); accCon.Close();
Problems:
Memory usage is very high (300MB ++), while the MS Access file size does not change all the time! The insert seems to cache the data, not save it to disk.
It is very slow! I know that my request is completed in a few seconds, but the insertion process is time consuming.
I tried to use the prepared statement in MS Access and insert the values ββas parameters instead of the concat string to create an insert request. However, I get this exception message:
Data type mismatch in criteria expression.
Does anyone know how to fix this or have a better approach?
c # mysql ms-access odbc oledb
Masoud
source share