VB.NET 2010:错误“ErrorExecuteReader:连接属性尚未初始化”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15262478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:38:58  来源:igfitidea点击:

VB.NET 2010: Error "ErrorExecuteReader: Connection property has not been initialized"

vb.netvisual-studio-2010visual-studio

提问by beginnerVB.Net

I'm getting this error: "ErrorExecuteReader: Connection property has not been initialized"

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

I can't figure out what the problem is.

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

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

回答by anon

The connection property of your command object hasn't been set. Add it to your constructor like so:

您的命令对象的连接属性尚未设置。将它添加到您的构造函数中,如下所示:

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

Or set the Connection property like so:

或者像这样设置 Connection 属性:

cmd.Connection = conn

By the way, this error should have been easy to catch if you were debugging in Visual Studio.

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