Click here to Skip to main content
15,888,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all,

i am saving data from CSV file to access database , My CSV file data contains numeric fields with null values and text fields contains single quotes.

trying to insert the data i am getting error:

Data type mismatch in criteria expression.

in below code text fields ACCT,SHORT,DESC1 fields are having single quote data.

numeric fields PRINC,[GROSS],[STAND],[NET],[NEWNET],[AECHG],[BONUS],[ORDER],[REALGR],[ANNUITYNET],[RECORDID] fields are having null values.

How to handle with this.


My code is like below.

 public DataTable InserttblDetailOPSData(string sInputPath, string sInFile)
        {
            string query = string.Empty;
            string header = "Yes";
            DataTable dataTable = null;
            string filePath = string.Empty;
            string fileName = string.Empty;
            sInputPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\";
            sInFile = WebConfig.GetSetting("InFileName");

            try
            {

                //csv file directory
                filePath = sInputPath;
                //csv file name
                fileName = WebConfig.GetSetting("InFileName");

                query = @"SELECT * FROM [" + fileName + "]";

                using (OleDbConnection connection = new OleDbConnection((@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Text;HDR=" + header + "\"")))
                {
                    using (OleDbCommand command = new OleDbCommand(query, connection))
                    {
                        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
                        {
                            dataTable = new DataTable();
                            dataTable.Locale = CultureInfo.CurrentCulture;
                            adapter.Fill(dataTable);

                            try
                            {
                                //create connection to Access DB
                                OleDbConnection DBconn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + WebConfig.GetSetting("AccessDBFilePath.devdesktop"));
                                OleDbCommand cmd = new OleDbCommand();
                                //set cmd settings
                                cmd.Connection = DBconn;
                                cmd.CommandType = CommandType.Text;
                                //open DB connection
                                DBconn.Open();
                                //read each row in the Datatable and insert that record into the DB
                                for (int i = 0; i < dataTable.Rows.Count; i++)
                                {
                                    cmd.CommandText = "INSERT INTO tblDetail ([OFFICE],[AE],[SETDATE],[ACCT],[SHORT],[BS],[SHARES],[DESC],[PRICE],[PRINC],[GROSS],[STAND],[NET],[NEWNET],[AECHG],[BONUS],[BT],[CANCEL],[TRANSCODE],[ORDER],[REALGR],[ANNUITYNET],[RECORDID],[USERCODE1],[USERCODE7])" +
                                                     " VALUES ('" + dataTable.Rows[i].ItemArray.GetValue(0) + "','" + dataTable.Rows[i].ItemArray.GetValue(1) + "','" + dataTable.Rows[i].ItemArray.GetValue(2) +
                                                     "','" + dataTable.Rows[i].ItemArray.GetValue(3) + "','" + dataTable.Rows[i].ItemArray.GetValue(4) + "','" + dataTable.Rows[i].ItemArray.GetValue(5) +
                                                     "','" + dataTable.Rows[i].ItemArray.GetValue(6) + "','" + dataTable.Rows[i].ItemArray.GetValue(7) + "','" + dataTable.Rows[i].ItemArray.GetValue(8) +
                                                     "','" + dataTable.Rows[i].ItemArray.GetValue(9) + "','" + dataTable.Rows[i].ItemArray.GetValue(10) + "','" + dataTable.Rows[i].ItemArray.GetValue(11) +
                                                     "','" + dataTable.Rows[i].ItemArray.GetValue(12) + "','" + dataTable.Rows[i].ItemArray.GetValue(13) + "','" + dataTable.Rows[i].ItemArray.GetValue(14) +
                                                     "','" + dataTable.Rows[i].ItemArray.GetValue(15) + "','" + dataTable.Rows[i].ItemArray.GetValue(16) + "','" + dataTable.Rows[i].ItemArray.GetValue(17) +
                                                     "','" + dataTable.Rows[i].ItemArray.GetValue(18) + "','" + dataTable.Rows[i].ItemArray.GetValue(19) + "','" + dataTable.Rows[i].ItemArray.GetValue(20) +
                                                     "','" + dataTable.Rows[i].ItemArray.GetValue(21) + "','" + dataTable.Rows[i].ItemArray.GetValue(23) + "','" + dataTable.Rows[i].ItemArray.GetValue(24) +
                                                     "','" + dataTable.Rows[i].ItemArray.GetValue(25) + "')";

                                    cmd.ExecuteNonQuery();
                                }
                                //close DB.connection
                                DBconn.Close();
                            }
                            catch (Exception ex)
                            {
                                //sendEmail(ConfigurationManager.AppSettings["QuantumEmailFrom"], ConfigurationManager.AppSettings["QuantumEmailTo"], "Quantum CSV Import To SMS Database FAILED", ex.Message);
                            }
                        }
                    }
                }
                //checks folder exists
                if (Directory.Exists(sInputPath))
                {
                    //deletes all folder contents and recreates an empty folder
                    Directory.Delete(sInputPath, true);
                    Directory.CreateDirectory(sInputPath);
                }
            }
            catch (Exception ex)
            {
                throw ex;
                //sendEmail(ConfigurationManager.AppSettings["QuantumEmailFrom"], ConfigurationManager.AppSettings["QuantumEmailTo"], "Quantum CSV Import To SMS Database FAILED", ex.Message);
            }

            return dataTable;
}


What I have tried:

in below code text fields ACCT,SHORT,DESC1 fields are having single quote data.

numeric fields PRINC,[GROSS],[STAND],[NET],[NEWNET],[AECHG],[BONUS],[ORDER],[REALGR],[ANNUITYNET],[RECORDID] fields are having null values.

How to handle with this.
Posted
Updated 5-Feb-18 9:50am
Comments
ZurdoDev 5-Feb-18 13:37pm    
That means you have the wrong type of data going into a field, like a string into a number field. You have to debug it and find out what is going on.

1 solution

First problem; you are concatenating strings and attempting to insert them.. Don't do this, you should use parameters when creating your INSERT statement else you are open to SQL injection - refer; How To: Protect From SQL Injection in ASP.NET[^]
Second problem; Your insert statement will end up looking like this;
SQL
INSERT INTO tblDetail (TextA, TextB, NumberA, NumberB)
VALUES ('Text Value A', 'Text Value B', 'Number1', 'Number2')

Notice the quotes around your numbers? This will normally work successfully, except when you have no value - A number column can accept a NULL value but not an empty string. Additionally, you have said that your text values are surrounded by quotes, make sure they are not being included.

Use your debugger, get the output of your Insert statement and attempt to insert your data in Access via the Query designer, you will quickly see why you are having an issue & how to resolve it.

If you insist on using string concatenation then at least use a StringBuilder, it makes your code easier to understand & update should requirements change.
MSDN - StringBuilder Class (System.Text)[^]

Kind Regards
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900