我目前正在使用SQL Server後端在Visual Studio 2013 Express中工作。我試圖做一個非常簡單的更新語句,但由於某種原因,這個東西不會運行。它開始挫敗我如何這個簡單的查詢不會運行。無法在vb.net中運行SQL更新語句,
此表格應該將零件號碼從一臺機器移至另一臺機器。我有3個組合框,combobox1是FromMachine,combobox2是機器,combobox 3是零件編號。
我的SQL Server表有一個零件號和切割機的列。所有這些都在按鈕單擊事件上運行。請注意,部件號是日期時間,機器是整數。這是我的代碼。
'Safety check
If Combobox1.SelectedIndex = -1 Then
MsgBox("Please select a machine to move the Part from.")
Exit Sub
End If
If Combobox2.SelectedIndex = -1 Then
MsgBox("Please select a machine to move the part to.")
Exit Sub
End If
If Combobox3.SelectedIndex = -1 Then
MsgBox("Please select a part number to change from one cutting machine to another.")
Exit Sub
End If
Dim FromMachine As Integer = Combobox1.SelectedValue
Dim ToMachine As Integer = Combobox2.SelectedValue
Dim Part As DateTime = Combobox3.SelectedValue
Try
'sql command for the change
'make sure that part isnt already on that machine
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("SELECT PartNumber FROM Table1 Where PartNumber = @PartNumber AND Machine = @ToMachine", conn1)
comm1.Parameters.AddWithValue("PartNumber", Part)
comm1.Parameters.AddWithValue("@ToMachine", ToMachine)
Dim dt As New DataTable
Dim sql As New SqlDataAdapter(comm1)
sql.Fill(dt)
DataGridView1.DataSource = dt
'check for data entries
If dt.Rows.Count > 0 Then
MsgBox("Part Number " & Combobox3.SelectedText & " is already assigned to " & Combobox2.SelectedText & ". This Part could not be changed.")
Exit Sub
Else
'Make the change
Using conn2 As New SqlConnection(connstring)
conn2.Open()
Using comm2 As New SqlCommand("UPDATE table1 SET Machine = @ToMachine Where Machine = @FromMachine " _
& "AND PartNumber = @PartNumber", conn1)
comm1.Parameters.AddWithValue("@ToMachine", ToMachine)
comm1.Parameters.AddWithValue("@FromMachine", FromMachine)
comm1.Parameters.AddWithValue("@PartNumber", PartNumber)
comm1.ExecuteNonQuery()
MsgBox("PartNumber " & Combobox3.SelectedText & " has been changed from cutting machine " & Combobox1.SelectedText & " To cutting machine " & Combobox2.SelectedText & ".")
End Using
conn2.Close()
End Using
End If
End Using
conn1.Close()
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
總之,組合框1是部件號被從移動的機器,並且combobox2是機器的是,APRT正在被移動了。第一個sql語句檢查該部分是否已經在該機器上,因爲相同的部分永遠不會在同一臺機器上被切割兩次。然後,如果datagridview返回什麼也沒有,那麼第二個sql語句將運行update語句。
此外,所有組合框都從SQL查詢中加載,並且當我添加監視它們或將SQL語句插入到我的可視化管理程序時,它們都具有正確的值。
---------- UPDATE -------------
的代碼並運行,我已經通過它加強,但是,一旦代碼完成沒有對SQL Server進行更改。我已將SQL更新語句放入Management Studio並插入值,我在vb.net程序中卸下了手錶,並且它不會更改機器。它的行爲就像它正在執行代碼一樣,但沒有將其應用到SQL Server。
------------更新------------- 錯誤是使用comm1的comm1參數並在comm2下執行comm1。
而不是'AddWithValue'從參數值推斷(可能不正確的)類型使用'Add(sqlParameterWithType).Value = value'。 –
什麼不運行?你有錯誤嗎?你是否瀏覽了代碼? – Tim
@Tim我已經瀏覽了代碼,並且沒有收到錯誤消息。一旦代碼運行,我再次檢查它在服務器上,它只是沒有做出改變。我已經添加了一個監視所有我的變量,他們都正確的SQL語句運行。 – Cheddar