我正在尝试使用两个变量从winform执行更新查询,而不使用数据集。 我分配了我的两个变量,然后运行查询,但它不断给出zcomp不是有效列名的错误。当然这是真的,但在我说= zcomp之前我告诉它哪一列。下面是我运行查询的代码。
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并放入变量中的实际数值,它就可以正常工作。请帮助我整天都在搜索使用此更新查询的变量的方法。 谢谢, 斯泰西
答案 0 :(得分: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"
答案 1 :(得分:0)
除了使用参数之外,“Using”语句还会关闭连接并处理资源:
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
答案 2 :(得分: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