我使用带有参数的vb.net创建了一个查询,该查询应该允许查询从我的访问数据库中检索数据,但是当我点击按钮时它只显示空白字段但没有从数据库中检索到的行。你能帮我解决一下我目前做错的事吗。
Imports System.Data.OleDb
Public Class RouteToCruise
Private Sub RouteToCruise_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Route_Btn_Click(sender As Object, e As EventArgs) Handles Route_Btn.Click
Try
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT Route.RouteName + ', ' + Cruise.CruiseID As CruiseRoute FROM Route INNER JOIN Cruise ON Route.RouteID = Cruise.RouteID WHERE CruiseID = ?"
Dim cmd As New OleDbCommand(CruiseQuery, cn)
'cmd.Parameters.AddWithValue("CruiseID", OleDbType.Numeric).Value = Route_Txt.Text
cmd.Parameters.AddWithValue(("CruiseID"), OleDbType.Numeric)
Dim reader As OleDbDataReader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "RouteName"
While reader.Read
Dim rID As String = reader("RouteID").ToString()
cmd.Parameters.AddWithValue("?", rID)
row = reader("CruiseID") & "," & ("RouteName")
RCTable.Rows.Add(row)
End While
reader.Close()
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
结束班
如果用户在文本框中输入路线名称,则行应显示每条所选路线的巡航ID和路线名称。例如,如果用户在文本框中输入亚洲,则单击按钮,然后查询应返回前往亚洲的巡航的cruiseID。
答案 0 :(得分:1)
您对参数的使用毫无意义。首先调用AddWithValue
并且不提供任何值,然后执行查询,然后在读取数据时开始添加更多参数。您可以调用AddWithValue
并提供值,也可以调用Add
,然后在创建的参数对象上设置Value
。无论哪种方式,它必须在您执行查询之前,否则它是无用的。
myCommand.Parameters.AddWithValue("@ParameterName", parameterValue)
或
Dim myParameter = myCommand.Parameters.Add("@ParameterName", OleDbType.Numeric)
myParameter.Value = parameterValue