0

我收到此错误:"ErrorExecuteReader: Connection property has not been initialized"

我无法弄清楚问题是什么。

Imports System.Boolean
Imports System.Data.SqlClient

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim userID As String
        Dim password As String
        Dim conn As SqlConnection
        Dim cmd As SqlCommand
        Dim reader As SqlDataReader

        userID = txtuser.Text
        password = txtpassword.Text
        txtuser.Text = Focus()
        txtpassword.Visible = "False"

        Try
            conn = New SqlConnection("Data Source=XXXXXX;Initial Catalog=XXXXXXUser ID=XXXXXX;Password=XXXXXX")
            cmd = New SqlCommand("Select user,password from userlog where user='" + userID + "' & password='" + password + "'")

            conn.Open()
            reader = cmd.ExecuteReader()

            conn.Close()    

            If (String.Compare(password, 123) = 0) Then
                MsgBox("Success")
            End If
        Catch ex As Exception
            MsgBox("Error" + ex.Message())
        End Try
    End Sub
End Class
4

1 回答 1

4

您的命令对象的连接属性尚未设置。像这样将它添加到您的构造函数中:

cmd = New SqlCommand("...", conn)

或者像这样设置 Connection 属性:

cmd.Connection = conn

顺便说一句,如果您在 Visual Studio 中进行调试,应该很容易发现此错误。

于 2013-03-07T03:41:27.300 回答