4

VB で SQL サーバーからのクエリ結果を表示しようとしています。次のコードを書きましたが、「結果を表示するだけ」の方法がわかりません。

 Public Function ConnectToSQL() As String
        Dim con As New SqlConnection
Try
            con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm"
            Dim cmd As New SqlCommand("SELECT username FROM users WHERE username='user'", con)
            con.Open()
            Console.WriteLine("Connection Opened")

            ' Execute Query
            Dim reader As SqlDataReader = cmd.ExecuteReader()
            While reader.Read()
                Console.WriteLine(String.Format("{0}, {1}", _
                   reader(0), reader(1)))

            End While
        Catch ex As Exception
            MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
        Finally
            con.Close() 'Whether there is error or not. Close the connection.
        End Try
        Return reader
    End Function

誰でもガイドできますか?ありがとうございました

4

1 に答える 1

5

私はいくつかのことを修正しましたが、今あなたの関数は私にとってはうまくいきます:

Public Function ConnectToSQL() As String
    Dim con As New SqlConnection
    Dim reader As SqlDataReader
    Try
        con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm"
        Dim cmd As New SqlCommand("SELECT username, WindowsLogin FROM users WHERE username='user'", con)
        con.Open()
        Console.WriteLine("Connection Opened")

        ' Execute Query    '
        reader = cmd.ExecuteReader()
        While reader.Read()
            Console.WriteLine(String.Format("{0}, {1}", _
               reader(0), reader(1)))
            'NOTE: (^^) You are trying to read 2 columns here, but you only        '
            '   SELECT-ed one (username) originally...                             '
            ' , Also, you can call the columns by name(string), not just by number '

        End While
    Catch ex As Exception
        MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
    Finally
        con.Close() 'Whether there is error or not. Close the connection.    '
    End Try
    'Return reader { note: reader is not valid after it is closed }          '
    Return "done"
End Function

ご不明な点がございましたら、お知らせください。

于 2012-04-09T00:09:10.923 に答える