【问题标题】:SQL read data from table in vbSQL从vb中的表中读取数据
【发布时间】:2009-05-23 01:04:18
【问题描述】:

我正在尝试从数据中获取单个字段。 (我正在按主键搜索,所以我应该得到 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

【问题讨论】:

  • 无数据时读取无效

标签: sql sql-server vb.net


【解决方案1】:

您需要先读取数据读取器才能将其放在第一行。

所以不是

reader = sqlcmd.ExecuteReader()    
result = reader.GetString(0)

您可以像这样插入 Read() 方法:

reader = sqlcmd.ExecuteReader()    
if reader.Read() then '' <<<<< newly inserted code
    result = reader.GetString(0)
end if

【讨论】:

  • 不是我想要的……但没有错误!在正确方向迈出的一步!谢谢!
【解决方案2】:
''// 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多