2

我正在尝试在不使用数据集的情况下从带有两个变量的 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 并将实际数值放入变量中,它就可以正常工作。请帮助我一整天都在寻找一种在此更新查询中使用变量的方法。谢谢,斯泰西

4

3 回答 3

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
于 2013-08-08T04:00:22.853 回答
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
于 2012-11-06T21:23:16.987 回答
0

您可能正在寻找如何在 ADO.NET 中使用参数。对于您的示例,它可能如下所示:

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

将这两行放在前面的任何位置ExecuteNonQuery

因为参数需要@前缀,所以您还需要将查询更改为 say@zamnt而不是 just zamnt,并且对于zcomp:

cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - @zamnt WHERE [ComponentID] = @zcomp"
于 2012-11-06T21:11:23.350 回答