[英]How to add vb.net condition inside MySql query
我正在使用Datagridview
並獲取單元格值。 我需要做的是,當一個pieces
的細胞內的字符串值DatagridView
話,我改變我的查詢為“無”。 我已經在使用case
查詢,並且我認為這不是解決我的問題的正確答案。 你能幫我嗎? 順便說一下,這是我的代碼,我已經完成了。
For k As Integer = 0 To dtgOrder.RowCount - 1
objconn.Open()
cmbQuery = "SELECT product_quantity.Quantity As 'quant_test' from product_quantity
INNER join product_table on product_quantity.Product_ID = product_table.Product_ID
where product_size.Size_Name
= '" & If dtgOrder.Rows(k).Cells(3).Value = "pieces" Then
dtgOrder.Rows(k).Cells(3).Value = "None"
End If & "'"
objcmd = New MySqlCommand(cmbQuery, objconn)
objdr = objcmd.ExecuteReader
While objdr.Read
quantitytesting = objdr.GetInt32("quant_test")
End While
objconn.Close()
Next
這是我已經在使用MySQL的Case
進行的查詢,我也已經在上述查詢中應用了它。
SELECT product_quantity.Quantity As 'quant_test' from product_quantity
INNER join product_table on product_quantity.Product_ID = product_table.Product_ID
where product_size.Size_Name
= (Case when '"& dtgOrder.Rows(k).Cells(3).Value = "pieces" &"' Then 'None' Else '"& dtgOrder.Rows(k).Cells(3).Value &"')"
首先,也是最重要的一點是要了解的是, 永遠不要使用字符串連接將值放入SQL查詢中。 到目前為止,您所擁有的代碼只是乞求讓您的數據庫被黑客入侵。
順便說一下,這里有兩種可能的解決方案。
在VB中:
Const SQL As String = _
"SELECT product_quantity.Quantity As 'quant_test' " &
" FROM product_quantity " &
" INNER join product_table on product_quantity.Product_ID = product_table.Product_ID " &
" WHERE product_size.Size_Name = @SizeName"
= '
Using cn As New MySlConnection("connection string here"),
cmd As New MySqlCommand(SQL, cn)
Dim p As MySqlParameter = cmd.Parameters.Add("@SizeName", MySqlDbType.VarString)
cn.Open()
For Each row As DataGridViewRow In dtgOrder.Rows
p.Value = If(row.Cells(3).Value = "pieces", "None", row.Cells(3).Value)
Using objdr As MySqlDataReader = cmd.ExecuteReader()
While objdr.Read
quantitytesting = objdr.GetInt32("quant_test")
End While
End Using
Next
End Using
與原始代碼相比,此代碼有許多重要的改進,因此請研究該模式以備將來使用。 但是,當我在這里時,我還要補充一點,在帶有DataGridView的循環中看到這樣的查詢非常奇怪。 該DataGridView中的行幾乎可以肯定來自數據庫,這意味着您應該能夠構建單個查詢來產生結果,而根本不需要任何循環。 將其放入單個查詢將比使數據庫多次運行好得多 。
在SQL中:
Const SQL As String = _
"SELECT product_quantity.Quantity As 'quant_test' " &
" FROM product_quantity " &
" INNER join product_table on product_quantity.Product_ID = product_table.Product_ID " &
" WHERE product_size.Size_Name = COALESCE(NULLIF(@SizeName, 'pieces'),'None')"
= '
Using cn As New MySlConnection("connection string here"),
cmd As New MySqlCommand(SQL, cn)
Dim p As MySqlParameter = cmd.Parameters.Add("@SizeName", MySqlDbType.VarString)
cn.Open()
For Each row As DataGridViewRow In dtgOrder.Rows
p.Value = row.Cells(3).Value
Using objdr As MySqlDataReader = cmd.ExecuteReader()
While objdr.Read
quantitytesting = objdr.GetInt32("quant_test")
End While
End Using
Next
End Using
在這兩個I選項中,我更喜歡第一個...使客戶端應用程序執行此特定工作,而不是數據庫。 我發布此消息是因為,如果您確實嘗試將其簡化為單個SQL語句,則可能需要此邏輯才能使其正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.