2014-06-26 19 views
0

我想更新,其中列名會在文本框中,同時執行將進入一個表的列在文本框中specifed列。以下代碼不執行任何操作。 TextBox14包含列名稱,TextBox12包含要更新的值。更新從服務器

 Dim squery As String = "SELECT name,days from definedLeave" 
         Dim cmd6 As SqlCommand = New SqlCommand(squery, con) 
         Dim dr6 As SqlDataReader = cmd6.ExecuteReader() 
         Dim i As Integer = 0 
         While dr6.Read() 
          Try 
           s = dr6(i).ToString 
           TextBox14.Text = s 
           a = dr6(i + 1).ToString 
           TextBox12.Text = a 
           Dim sql = "update empLeave set " & TextBox14.Text.Trim & "[email protected] where epid='" + txtCode.Text + "'" 

           Using com7 = New SqlCommand(sql, con) 
            com7.Parameters.AddWithValue("@na", TextBox12.Text) 
            com7.ExecuteNonQuery() 
           End Using 
          Catch ex As Exception 
     MsgBox("HELLO") 
    End Try 
         End While 
         com7.Dispose() 
         dr6.Close() 

回答

0

不幸的是,參數只能用於數值,不是標識符。它們就像VB中的變量 - 你不能用一個變量的內容來代表VB中的另一個變量。

愚蠢的是,你試圖使用一個參數,你不能,然後在哪裏可以,對於epid值,你使用字符串連接。你的代碼應該是這個樣子:

Dim sql = "UPDATE empleave SET [" & TextBox14.Text & "] = @na WHERE epid = @epid" 

Using com7 = New SqlCommand(sql, con) 
    com7.Parameters.AddWithValue("@na", TextBox12.Text) 
    com7.Parameters.AddWithValue("@epid", txtCode.Text) 

    com7.ExecuteNonQuery() 
End Using 

這仍然留下你雖然打開SQL注入,所以你應該絕對確保你第一次驗證列名。實際上,你應該做的是查詢數據庫以獲取列名,然後將它們放入ComboBox。這樣你可以保證用戶將選擇一個有效的值。

+0

@ jimcilhinney格式不起作用。實際上,我已經從另一個表中取得內容作爲該表的列名。我已經用完整的代碼編輯了代碼部分。請檢查 – user3774245

+0

也許你可能比「不起作用」更具體一些。當你已經知道實際發生的事情時,我們猜測它是沒有意義的。錯誤消息不提供有趣的;他們是爲了獲取信息。 – jmcilhinney

+0

我沒有收到任何錯誤,但表格沒有更新 – user3774245

0

嘗試這樣

Dim sql as string= "update empLeave set " & TextBox14.Text.Trim & "[email protected] where 
epid='" + txtCode.Text + "'" 

    Using com7 = New SqlCommand(sql, con) 
     com7.Parameters.AddWithValue("@na", TextBox12.Text) 
     com7.ExecuteNonQuery() 
    End Using 
+0

我嘗試了上面的代碼,但它的工作。表沒有得到更新,dosent得到任何錯誤信息。 – user3774245

+0

你檢查了你的查詢嗎?發佈您的查詢 – Sathish

+0

Dim sql =「update empLeave set」&TextBox14.Text.Trim&「= @ na where epid ='」+ txtCode.Text +''「 使用com7 =新建SqlCommand(sql,con) com7。 Parameters.AddWithValue(「@吶」,TextBox12.Text) com7.ExecuteNonQuery() 結束檢查的字符串返回分配在SQL – user3774245