2011-09-19 135 views
1

我試圖動態地使用我的預訂表單中的文本框值來生成一個查詢,以僅更新用戶輸入的那些值。在VB.Net中動態更新SQL Server數據庫

我使用下面的代碼:

Dim str As String 

str = "UPDATE Bookings SET " 
Dim first As Integer = 1 
For Each x As Control In Me.Controls 
    If x.GetType Is GetType(TextBox) Then 
     If first = 1 Then 
      first = 2 
     Else 
      str &= "," 
     End If 
     If x.Tag = 1 Then 
      str = str & x.Name & " = @" & x.Name 
     End If 
    End If 
Next 

但它產生這樣的查詢:

Update Bookings SET ,,booking_date = @booking_date,,,,,cust_name = @cust_name where bookingID = @bookingID 

或者,如果我想更新僅有1場它生成此:

Update Bookings SET ,,,,,,,cust_name = @cust_name where bookingID = @bookingID 
+1

我知道這並不回答你的問題,但請考慮使用SQLCommand和SQLParameters,如果此代碼是爲生產使用。像這樣生成SQL是一個巨大的安全漏洞:) –

+0

我已經使用sqlcommand和sql參數,並且此代碼僅用於在運行時爲具有值的文本框生成查詢 –

回答

1
Dim str As String 
str = "UPDATE Bookings SET " 
Dim comma As string = "" 
For Each x As Control In Me.Controls 
    If x.GetType Is GetType(TextBox) Then 
    If x.Tag = 1 Then 
     str &= comma & x.Name & " = @" & x.Name 
     comma = "," 
    End If 
    End If 
Next 

這裏是th e一行答案。

Dim str = "UPDATE Bookings SET " & String.Join(",", (From _E In Controls.OfType(Of Control)() Where _E.GetType() Is GetType(TextBox) AndAlso _E.Tag = "1" Select _E.Name).ToList()) 
+0

我有2個蒙版文本框1是cust_id及其蒙版是「csc-」,即在csc-之後需要四個整數值,另一個是掩碼爲「 - 」的接點,即在' - '之前需要四個整數值,在'-'之後需要7個整數值。 ..但是這兩個文本框都沒有得到驗證,我已經在驗證的事件中放置了.tag = 1,並且我也在textchanged事件中嘗試了它,但沒用,並且如果在這兩個文本框中輸入某些值,查詢不會更改。請爲此提出一個補救措施 –