好吧,我遇到了一个需要在星期三之前完成的重大项目的障碍,而且我刚刚站了起来。我需要通过VB运行以下SQL Query来获取我的程序中使用的一些数据:
SELECT Pay FROM Players
WHERE (Name = @Name)
是的,我正在尝试向查询发送一个参数,因为我不想要整个列,而只是列中的单个条目,因此是WHERE子句。现在,考虑到这一点,我该怎么称呼它?
这是我在我的程序中使用的当前代码:
Public Class frmName
Private mNames As New Names
Private Sub frmName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboSelect.DataSource = mNames.Names
cboSelect.DisplayMember = "Name"
cboSelect.ValueMember = "Name"
'TODO: This line of code loads data into the 'RRBCDataSet.Players' table. You can move, or remove it, as needed.
'Me.PlayersTableAdapter.Fill(Me.RRBCDataSet.Players)
End Sub
Private Sub btnSelect_Click(sender As Object, e As EventArgs) Handles btnSelect.Click
End Sub
现在,是的,这实际上是用户被提示从ComboBox列表中选择棒球队中的球员,该球员将球员预先加载到选择列表中。我的问题是,当用户点击“选择”时,如何调用查询?从那里开始,接下来的计算我已经在另一个模块中作为一系列函数和方法得到了解决。
答案 0 :(得分:1)
Private Sub btnSelect_Click(sender As Object, e As EventArgs) Handles btnSelect.Click
Dim SQL As String = "SELECT Pay FROM Players WHERE Name = @Name"
Using cn As New SqlConnection("Connection string here"), _
cmd As New SqlCommand(SQL, cn)
'Change the "50" here to match the exact size of the database column
cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = cboSelect.SelectedValue
cn.Open()
'money should always use the decimal type
Dim pay As Decimal = Convert.ToDecimal(cmd.ExecuteScalar())
'At this point, the "pay" variable declared above has your database result.
'You haven't indicated yet what you want to do with it
End Using
End Sub