Retrieving “Number” From Sql VB.NET System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.'

♀尐吖头ヾ 提交于 2021-01-29 18:36:26

问题


If I want to retrieve a value that is saved as a number in an access database.

Im using the following:

            Dim sql As String = "SELECT ArithmeticScore FROM " & tablename & " WHERE DateAscending = '" & todaysdate & "'"
            Using connection As New OleDbConnection(getconn)
                Using command As New OleDbCommand(sql, connection)
                    connection.Open()
                    scorevalue = CDec(command.ExecuteScalar()) 'Data type mismatch in criteria expression.
                    connection.Close()
                End Using
            End Using
            MsgBox(scorevalue)

getconn = connection string as a string

scorevalue = Nothing as decimal

The field ArithmeticScore is set to Number in the table.

The exact value in the cell right now is 50, but the program should allow for any decimal value.

The error im getting is "Data type mismatch in criteria expression".


回答1:


The criteria expression mentioned in the error message does not refer to the ArithmeticScore output. It's talking about the WHERE clause. Whatever you have for todaysdate does not match what the database is expecting for the DateAscending column.

Since OleDb is a generic provider, we don't know exactly what kind of database you're talking to, but most databases have a way to get the current date value in SQL: getdate(), current_timestamp, etc. Using that mechanism will likely solve the conflict, and there's no need to use string concatenation for this in the first place.

Dim sql As String = "SELECT ArithmeticScore FROM " & tablename & " WHERE DateAscending = Date()"

The other way you can fix this is with proper parameterized queries, which you should doing anyway. It's NEVER okay to use string concatenation to substitute data into an SQL query, and if you find yourself needing to think about how to format a date or number string for use in an SQL command, you're almost always doing something very wrong.



来源:https://stackoverflow.com/questions/61463370/retrieving-number-from-sql-vb-net-system-data-oledb-oledbexception-data-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!