2012-11-06 37 views
2

我想從一個winform更改查詢與兩個變量不使用數據集。 我分配了我的兩個變量,然後運行查詢,但它一直給出zcomp不是有效列名的錯誤。哪一個當然是對的,但我會告訴它在我說= zcomp之前的哪一列。以下是我的代碼運行查詢。使用where子句與VS2010中的變量SQL更新Winforms

Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value 
Dim zcomp As Integer = gridRow.Cells(0).Value 

Dim con As New SqlConnection 
Dim cmd As New SqlCommand 
Try 
    con.ConnectionString = "Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True" 
    con.Open() 
    cmd.Connection = con 
    cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - zamnt WHERE [ComponentID] = zcomp" 
    cmd.ExecuteNonQuery() 
Catch ex As Exception 
    MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records") 
Finally 
    con.Close() 
    gridRow.Cells(4).Value = "Yes" 
End Try 

我嘗試了幾種不同的方法。如果我取出zamnt和zcomp並將實際的數值放入變量中,它工作得很好。請幫助我一直在尋找一種方法來使用這個更新查詢的變量。 謝謝, Stacy

回答

0

您可能正在尋找如何在ADO.NET中使用參數。爲了您的例子,它可以是這樣的:

cmd.Parameters.Add("@zamnt", zamnt); 
cmd.Parameters.Add("@zcomp", zcomp); 

ExecuteNonQuery之前的任何地方把這兩行。

由於參數需要一個@前綴,你也需要改變你的查詢說@zamnt,而不是僅僅zamnt,和同爲zcomp

cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - @zamnt WHERE [ComponentID] = @zcomp" 
0

除了使用參數,「使用」的聲明關閉連接並配置資源:

Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value 
    Dim zcomp As Integer = gridRow.Cells(0).Value 

    Try 
     Using con As New SqlConnection("Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True") 
      con.Open() 
      Using cmd As New SqlCommand 
       cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - @zamnt WHERE [ComponentID] = @zcomp" 
       cmd.Parameters.AddWithValue("@zamt", zamnt) 
       cmd.Parameters.AddWithValue("@zcomp", zcomp) 
       cmd.ExecuteNonQuery() 
      End Using 
     End Using 
    Catch ex As Exception 
     MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records") 
    Finally 
     con.Close() 
     gridRow.Cells(4).Value = "Yes" 
    End Try 
+0

不是AddWithValue()的粉絲。它有一些類型相關的陷阱。 –

0

你試過嗎?

Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value 
Dim zcomp As Integer = gridRow.Cells(0).Value 

Dim con As New SqlConnection 
Dim cmd As New SqlCommand 
Try 
    con.ConnectionString = "Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True" 
    con.Open() 
    cmd.Connection = con 
    cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] -" + zamnt + " WHERE [ComponentID] =" + zcomp 
    cmd.ExecuteNonQuery() 
Catch ex As Exception 
    MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records") 
Finally 
    con.Close() 
    gridRow.Cells(4).Value = "Yes" 
End Try