简体   繁体   English

Visual Studio 2013 SQL数据读取器

[英]Visual Studio 2013 sql data reader

I'm only starting out with this. 我只是从这个开始。 I've been over numerous tutorials but I just can't get this to work. 我已经看过许多教程,但是我无法使它正常工作。 I'm trying to fill a text box with a result but it is not working. 我正在尝试用结果填充文本框,但是它不起作用。 I've even put in a MsgBox("AA") to check that the reader has rows and the msgbox appears but still it does not fill the textbox with the value. 我什至放了一个MsgBox("AA")来检查读者是否有行并且出现了msgbox,但仍然没有用值填充文本框。

Option Explicit On
Option Strict On
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class CustEnquiry
Private Sub TextBox_LostFocus(sender As Object, e As EventArgs) Handles TextBox1.LostFocus
        Dim connectionString As String = _
            "Data Source=SERVER;Initial Catalog=DATABASE;" _
            & "Persist Security Info=True;User ID=USERID;Password=PASSWORD"
        Using connection As New SqlConnection(connectionString)
            Dim command As SqlCommand = New SqlCommand( _
           "SELECT FIELD FROM dbo.TABLE WHERE VALUE = '092902D';", _
           connection)
            connection.Open()
            Dim reader As SqlDataReader = command.ExecuteReader()
            If reader.HasRows Then
                MsgBox("AA")
                TextBox2.Text = reader.GetString(0)
            End If
            reader.Close()
        End Using
    End Sub
End Class

reader.Read() reader.Read()

i know that is short but that is the answer 我知道那很短,但这就是答案

You have to advance the reader to the next(first) record, therefore use Read : 您必须将阅读器前进到下一个(第一条)记录,因此请使用Read

If reader.HasRows Then
    reader.Read()
    MsgBox("AA")
    TextBox2.Text = reader.GetString(0)
End If

HasRows just returns if there are records, it does not advance the reader. 如果有记录, HasRows只是返回,它不会使阅读器前进。 You could also use Read to check if there's at least one record in the result set. 您还可以使用Read来检查结果集中是否至少有一条记录。

If reader.Read() Then
    MsgBox("AA")
    TextBox2.Text = reader.GetString(0)
End If

Since you are selecting and expecting only a single value you could also use SqlCommand.ExecuteScalar instead of the reader: 由于您仅选择并期望一个值,因此您也可以使用SqlCommand.ExecuteScalar代替阅读器:

Dim field As Object = command.ExecuteScalar() ' is DbNull.Value if the field is null in the database '

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM