[英]Solution add textbox in SQL as string in vb.net
如果您看到下面的代碼有一個值(2000),那么解決方案是什么,那么我想將其更改為文本框,以便我可以自定義值。
謝謝
傑克
Dim sql As String = "update GSDTS as t1 inner join IFGTS as t2 on t1.[ITM] = t2.[ITM] set t1.[CIU] = t2.[PRSOBNET]+2000 WHERE GDN = 'A.04.01.002.001'AND PNM=@PNM"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("@PNM", ComboBox1.SelectedValue)
conn.Open()
cmd.ExecuteNonQuery()
End Using
您可以像這里一樣向您的查詢添加另一個參數
' Read the textbox value here'
Dim newValue as Integer
Int32.TryParse(txtInput.Text, newValue)
' Put the parameter placeholder instead of a constant'
Dim sql As String = "update GSDTS as t1 inner join IFGTS as t2
on t1.[ITM] = t2.[ITM]
set t1.[CIU] = t2.[PRSOBNET]+@addvalue
WHERE GDN = 'A.04.01.002.001'AND PNM=@PNM"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
' Add the other parameter and its value before the old one. See note below'
cmd.Parameters.AddWithValue("@addvalue", newValue)
cmd.Parameters.AddWithValue("@PNM", ComboBox1.SelectedValue)
conn.Open()
cmd.ExecuteNonQuery()
End Using
另外,看看如何用單行 Add 替換 AddWithValue。 AddWithValue 很危險,因為它在處理日期或小數時可能會歪曲您的值,並且使用字符串效率低下
** 重要的 **
您正在使用 OleDb 提供程序。 在這種情況下,參數的添加順序應與它們的占位符在字符串中出現的順序相同。 所以應該在@PNM 之前添加新參數,否則在執行查詢時會以錯誤的順序讀取它們。
您的 SQL 語法不適用於我知道的任何 RDBMS,並且您沒有標記后端。 這可能僅僅是它根本不起作用的一個原因,你應該從糾正它開始。 其次,不要使用 AddWithValue 而是 Add 並明確指定您的數據類型。 話雖如此,例如將 MS SQL 服務器作為后端:
Dim sql As String = <sql>UPDATE GSDTS
SET [CIU] = t2.[PRSOBNET] + @addVal
FROM GSDTS AS t1
INNER JOIN IFGTS AS t2
ON t1.[ITM] = t2.[ITM]
WHERE t1.GDN = 'A.04.01.002.001'
AND t1.PNM = @PNM;</sql>
Dim addVal As Integer = Nothing
If Integer.TryParse(txtAdd.Text, addVal) Then
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add("@addVal", OleDbType.Integer).Value = addVal
cmd.Parameters.Add("@PNM", OleDbType.VarChar).Value = ComboBox1.SelectedValue
conn.Open()
cmd.ExecuteNonQuery()
End Using
End If
請注意,變量聲明的順序與它們在查詢中使用的順序相同。 這是 OleDb(位置參數)的必要條件。 如果您的后端類似於 MS SQL 服務器,那么更喜歡使用后端特定的 SqlConnection、SqlCommand(那么您也可以使用命名參數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.