2013-10-18 13 views
0

這裏是我不能在我的代碼中使用插入查詢的東西存在,我SqlCommand寫着ExecuteNonQuery()不匹配等等等等錯誤在我的添加按鈕,SQL Server Management Studio中和Visual Basic 2010

值有誤

這裏是我的代碼

Dim con As New SqlClient.SqlConnection("Server=.\SQLExpress;AttachDBFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\Finals.mdf;Database=Finals;Trusted_Connection=Yes;") 

Dim cmd As New SqlClient.SqlCommand 
cmd.Connection = con 
cmd.CommandText = "Insert Into [Finals].[dbo].[Nokia] Values ('" & Unit.Text & "'),('" & Price.Text & " '),('" & Stack.Text & "'),('" & Processor.Text & "'),('" & Size.Text & "'),('" & RAM.Text & "'),('" & Internal.Text & "'),('" & ComboBox1.Text & "')" 

con.Open() 
cmd.ExecuteNonQuery() 
con.Close() 

問題是cmd.CommandText誰能幫幫我嗎?

+0

多少列都存在添加它之前的參數從字符串轉換爲十進制在名爲總決賽的表中? – Steve

+1

我建議您在插入時指定列,並在直接傳遞之前測試文本框是否填滿。 –

+0

Steve的列數與值的數量相同 – MaouAion

回答

4

您需要重寫查詢以使用參數化查詢。如果您的文本框包含單引號,這將避免解析問題,最重要的是,它將刪除Sql Injection的任何可能性。

所以,你的代碼看起來是這樣的

Dim cmdText = "Insert Into [Finals].[dbo].[Nokia] Values (@unit, @price,@stack," & _ 
       "@processor,@size,@ram,@internal,@lastvalue" 
Using con As New SqlConnection(......) 
Using cmd As New SqlCommand(cmdText, con) 
    con.Open() 
    cmd.Parameters.AddWithValue("@unit",Unit.Text) 
    cmd.Parameters.AddWithValue("@price",Price.Text) 
    cmd.Parameters.AddWithValue("@stack",Stack.Text) 
    cmd.Parameters.AddWithValue("@processor", Processor.Text) 
    cmd.Parameters.AddWithValue("@size",Size.Text) 
    cmd.Parameters.AddWithValue("@ram", RAM.Text) 
    cmd.Parameters.AddWithValue("@internal",Internal.Text) 
    cmd.Parameters.AddWithValue("@lastvalue", ComboBox1.Text) 
    cmd.ExecuteNonQuery() 
End Using 
End Using 

說,是兩個問題認識:

你不指定VALUES語句之前的列清單。這意味着您需要傳遞您的表中名爲Nokia AND的每個列的參數的確切數量,並以底層列的精確順序傳遞。如果你忘記了一個參數,你會收到一個異常,如果你交換了參數的順序,你最終將數據寫入錯誤的列(如果數據類型不匹配,那麼等待你的例外)。

第二個問題涉及傳遞給查詢的每個參數的數據類型。在你的情況下,你使用文本框的Text屬性,這意味着你正在爲數據表中的每一列傳遞一個字符串。當然,如果某個列需要數字值,則會出現不匹配錯誤。

例如,@price參數可以用來更新DataTable中的一個十進制列,因此你需要使用AddWithValue方法

cmd.Parameters.AddWithValue("@price",Convert.ToDecimal(Price.Text)) 
+0

我看到我的老師說我可以使用,但如果這是好得多然後生病使用這 – MaouAion

+0

顯示你的老師這個http://stackoverflow.com/questions/332365/how-does-the-sql-injection-from- the-bobby-tables-xkcd-comic-work – Steve

+0

@ user2882523我打算髮布完全相同的東西,它總是很好的建議去參數化查詢,我甚至會更進一步說,嘗試使用存儲過程而不是內聯SQL,通常他們被認爲是更好的選擇。 – Purplegoldfish

相關問題