![](/img/trans.png)
[英]How to fix System.FormatException: 'Input string was not in a correct format'
[英]How do i fix a “FormatException: Input string was not in a correct format”
我正在為我的學校項目做一些編碼,我正在嘗試創建一個使用過濾器並根據這些查詢顯示一組項目的程序。 但是,在編寫 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:輸入字符串的格式不正確。
我在哪里錯了?
我已經演示了如何使用參數。 您的主要問題在於查詢字符串中的邏輯。 由And
或Or
分隔的Where
子句的每個部分必須計算為 True 或 False。 想想看。 價格不能同時等於 Max 和 Min。 您將不得不檢查數據庫以查看字段的正確數據類型,因為我不得不猜測。 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.