vb.net - 如何修复“FormatException:输入字符串的格式不正确”
问题描述
我正在为我的学校项目做一些编码,我正在尝试创建一个使用过滤器并根据这些查询显示一组项目的程序。但是,在编写 SQL 语句时,我得到一个 FormatException。
这是我的代码行:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM partList WHERE [price] = '" & filterMinPrice And filterMaxPrice & "'AND [size] = '" & filterMicroATX And filterATX & "'AND [usability] = '" & filterHomeUse And filterSemiIntensive And filterHighIntensive)
这是我收到的错误:
System.InvalidCastException:“从字符串“SELECT * FROM partList WHERE [pr”到类型“Long”的转换无效。” FormatException:输入字符串的格式不正确。
我在哪里错了?
解决方案
我已经演示了如何使用参数。您的主要问题在于查询字符串中的逻辑。由orWhere
分隔的子句的每个部分必须计算为 True 或 False。想想看。价格不能同时等于 Max 和 Min。您将不得不检查数据库以查看字段的正确数据类型,因为我不得不猜测。该块确保连接被关闭和释放,命令被释放。And
Or
Using...End Using
Private ConStr As String = "Your connection string"
Private Function GetPartData(filterMinPrice As Decimal, filterMaxPrice As Decimal, filterMicroATX As Integer, filterATX As Integer, filterHomeUse As String, filterSemiIntensive As String, filterHighIntensive As String) As DataTable
Dim dt As New DataTable
Dim sql = "SELECT * FROM partList
WHERE [price] > @MinPrice
And [price] < @MaxPrice
AND [size] > @MicroATX
And [size] < @ATX
AND [usability] = @HomeUse
Or [usability] = @SemiIntensive
Or [usability] = @HighIntensive;"
Using con As New OleDbConnection(ConStr),
cmd As New OleDbCommand(sql, con)
With cmd.Parameters
.Add("@MinPrice", OleDbType.Decimal).Value = filterMinPrice
.Add("@MaxPrice", OleDbType.Decimal).Value = filterMaxPrice
.Add("@MicroATX", OleDbType.Integer).Value = filterMicroATX
.Add("@ATX", OleDbType.Integer).Value = filterATX
.Add("@HomeUse", OleDbType.VarChar).Value = filterHomeUse
.Add("@SemiIntensive", OleDbType.VarChar).Value = filterSemiIntensive
.Add("@HighIntensive", OleDbType.VarChar).Value = filterHighIntensive
End With
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
推荐阅读
- apache-spark - Spark Structured Streaming Kafka 错误——偏移量已更改
- javascript - 向原型中添加一个名为“speak”的方法
- google-sheets - 谷歌表格价值函数
- java - 如何使用流对这个 HashMap 进行展平和分组?
- angular - Angular /NgRx - 在 Effect 中传递泛型类型
- typescript - 在接口打字稿中支持静态和非静态方法
- javascript - 使用文件输入后,Javascript 警报会锁定 IOS Chrome 上的页面
- office365 - 为 Office 2019 和 365 创建 React 加载项
- javascript - Google Sheets API:batchGet 返回“未定义”
- spinnaker - 1.12.4 中缺少大三角帆 buildRpm 任务