我正在尝试从数据中获取单个字段。 (我正在用主键搜索,所以我应该得到0或1个答案)。请帮忙。我查询的表有一个条目,用户=某人,输入到几列,ans列有“一个好的答案”
Dim reader As SqlDataReader
Dim par As SqlParameter
Dim result As String
Dim sqlconn As SqlConnection
sqlconn = New SqlConnection("....")
sqlconn.Open()
Dim sqlcmd As SqlCommand
sqlcmd = New SqlCommand("Select Ans From Test Where User = @auser", sqlconn)
par = New SqlParameter
par.ParameterName = "auser"
par.Value = Textbox1.Text
sqlcmd.Parameters.Add(par)
reader = sqlcmd.ExecuteReader()
result = reader.GetString(0)
''//output to label
label1.Text = result
答案 0 :(得分:4)
您需要先读取数据读取器,然后将其放在第一行。
所以而不是
reader = sqlcmd.ExecuteReader()
result = reader.GetString(0)
您可以像这样插入Read()方法:
reader = sqlcmd.ExecuteReader()
if reader.Read() then '' <<<<< newly inserted code
result = reader.GetString(0)
end if
答案 1 :(得分:0)
''// using statement will guarantee the object is closed and disposed
''// even if an exception occurs
Using sqlconn As New SqlConnection("...."), _
sqlcmd As New SqlCommand("Select Ans From Test Where User = @auser", sqlconn)
''// you can create, add, and set the value for a parameter all on one line
sqlcmd.Parameters.Add("@auser", SqlDbType.VarChar, 50).Value = Textbox1.Text
''//wait as long as possible to open the connection
sqlconn.Open()
''// if you're only getting the first column of the first row, use execute scalar
label1.Text = CString(sqlcmd.ExecuteScalar())
End Using