简体   繁体   中英

Data Type Mismatch when evaluating Access Calculated Fields in Visual c# using Microsoft Access Database Engine

I have a OleDbCommand in a Visual Studios c# windows forms project, and I am trying to select the name of every item in my Access Table Stock where the value of a calculated field in that table is less than one. The result type of the calculated field in Access is set to decimal, and the code looks as if it should work, but for whatever reason it doesn't. Could you help me?

Here is my code:

        loginForm.connection.Open();
        stockLowString = "";
        var checkStockLowCommand = new OleDbCommand("SELECT stockName FROM Stock WHERE (stockLowCalculation < '" + Convert.ToDecimal(1) + "')",loginForm.connection);
        OleDbDataReader checkStockLowReader = checkStockLowCommand.ExecuteReader();
        while (checkStockLowReader.Read())
        {
            stockLowString = stockLowString + checkStockLowReader.GetString(0) + " ";
        }
        if (stockLowString != "")
        {
            MessageBox.Show("There are some Stock Items that are low, these are" + Environment.NewLine + stockLowString);
        }
        loginForm.connection.Close();

The error occurs on the line

OleDbDataReader checkStockLowReader = checkStockLowCommand.ExecuteReader();

Thanks in advance for your help.

Problem Solved, or at least avoided. I just put the calculation in the Command rather than use a calculated field. The question is still valid though, as I didn't solve it.

Open the database and check the type of the field "stockLowCalculation" it's most likely not decimal.. I suggest you rework your query and make it parametrized. This way you would evade most of the possible data type mismatch errors.

string conS ="..."; // connection string
var param = 1;
using (var connection = new OleDbConnection(conS))
{
       string queryString = "SELECT stockName FROM Stock WHERE stockLowCalculation < @var"
       var cmd = new OleDbCommand(queryString, connection);
       cmd.Parameters.Add(new OleDbParameter("@var", param));
       connection.Open();
       OleDbDataAdapter adapt = new OleDbDataAdapter(cmd);                    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM