我尝试从我的SQL中选择第一行和第一项 但是,它显示消息“找不到行0”
sqlCmd1 = "SELECT Type.Name FROM Type INNER JOIN Room ON Type.TID = Room.TypeID WHERE (((Room.ROID)= " + (roomCB.SelectedIndex + 1).ToString() + "));"
ad = New OleDb.OleDbDataAdapter(sqlCmd1, cnn)
ds = New DataSet
ad.Fill(ds)
Try
typeTxt.Text = ds.Tables(0).Rows(0).Item(0)
Catch ex As Exception
MsgBox(ex.Message)
End Try
答案 0 :(得分:0)
如果您只想检索一个字段,为什么要填写DataTable?
ExecuteScalar
执行查询,并返回查询返回的结果集中第一行的第一列。其他列或行将被忽略。
此外,您应该使用参数化查询以避免SQL注入。
脱离我的头顶......
Dim RoomID As String = roomCB.SelectedIndex + 1.ToString()
Dim sql As String = "SELECT Type.Name FROM Type INNER JOIN Room ON Type.TID = @parameter"
Using cn As New SqlConnection("Your Connection string here"), _
cmd As New SqlCommand(sql, cn)
cn.Open()
cmd.Parameters.Add("@parameter", SqlDbType.VarChar, 50).Value = RoomID
typeTxt.Text = cmd.ExecuteScalar().ToString()
cn.Close()
End Using