首页 > 解决方案 > 如何修复“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:输入字符串的格式不正确。

我在哪里错了?

标签: vb.net

解决方案


我已经演示了如何使用参数。您的主要问题在于查询字符串中的逻辑。由orWhere分隔的子句的每个部分必须计算为 True 或 False。想想看。价格不能同时等于 Max 和 Min。您将不得不检查数据库以查看字段的正确数据类型,因为我不得不猜测。该块确保连接被关闭和释放,命令被释放。AndOrUsing...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

推荐阅读