简体   繁体   中英

system.data.oledb.oledbexception data type mismatch in criteria expression

I Try to check if the number exist in the table, when i use string and text in the database there is no problem but when i use a decimal (12345.5) and number in the database i have a data type mismatch in criteria expression. My database is MSAccess.

string OleDbValuecheck =
    "SELECT Table1.Number FROM Table1 WHERE Table1.Number =  '"+ (result) + "' ";
OleDbCommand cmd2 = new OleDbCommand(OleDbValuecheck, conn);
OleDbDataAdapter sd2 = new OleDbDataAdapter(cmd2);
DataTable dt2 = new DataTable();
sd2.Fill(dt2);
if (dt2.Rows.Count > 0)
{
    return false;
}

Table1.Number sounds like a number ;-) but you treat it as a character field in the SQL (you enclose it in quotes). Remove those quotes. Also, your C# code tries to concatenate result with implicit conversion to string, which may result in unexpected values like scientific notation, make it explicit with a predictable format.

string OleDbValuecheck =
    "SELECT Table1.Number FROM Table1 WHERE Table1.Number = "+ (result.ToString("0.00"));

We don't know what is/can be in result ; make sure that the format you choose in the conversion (ToString()) does not lose any precision.

Update: Also, you said you are taking result from the Text property of an MsAccess form textbox control. This property returns the text displayed on the form, as formatted, therefore it would have thousands delimiters (if the underlying number is 1234.5 and the textbox's format is set to 'Standard', for example, the .Text property would return 1,234.50 . I suggest that you change TextBox.Text to Textbox.Value, or remove the thousands delimiters by result.Replace(',','')

Don't do clumsy replacement. Do it right and apply the InvariantCulture that always uses a dot as the decimal separator:

Decimal result = 12345.5M;
var invariantCulture = System.Globalization.CultureInfo.InvariantCulture;
string resultText = result.ToString(invariantCulture);

Console.WriteLine(resultText);
// 12345.5

// then:

string OleDbValuecheck =
    "SELECT Table1.Number FROM Table1 WHERE Table1.Number = " + resultText + "";

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