.net:如何评估此错误

时间:2013-11-09 06:12:33

标签: vb.net error-handling database-connection connection-string

我是vb.net的新手,我正在尝试创建一个登录表单但是在运行此代码时出现错误msg("ExecuteReader: Connection property has not been initialized.")

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class Form1
    Dim con As New System.Data.OleDb.OleDbConnection
    Dim cmd As System.Data.OleDb.OleDbCommand
    Dim da As System.Data.OleDb.OleDbDataAdapter
    Dim sdr As System.Data.OleDb.OleDbDataReader

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim dbprovider As String = "Provider=Microsoft.jet.OleDb.4.0;"
        Dim dbsource As String = "Data Source=C:\Users\RAJKRI\Documents\Visual Studio 2008\Projects\Banking System.mdb"
        con.ConnectionString = dbprovider & dbsource
        con.Open()
        cmd.Connection = con
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\RAJKRI\Documents\Visual Studio 2008\Projects\Banking System.accdb")

        cmd = New OleDb.OleDbCommand("SELECT * FROM Login WHERE Empid = '" & TextBox1.Text & "' AND password = '" & TextBox2.Text & "' , con")
        sdr = cmd.ExecuteReader()
        If (sdr.Read() = True) Then
        Form2.Show()
        TextBox1.Text = ""
        TextBox2.Text = ""

        Else
        MessageBox.Show("Invalid Employee Id/Password")

        End If
    End Sub

     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        TextBox1.Text = ""
        TextBox2.Text = ""
    End Sub
End Class

1 个答案:

答案 0 :(得分:2)

您将连接对象作为文本追加到查询中。变化

cmd = New OleDb.OleDbCommand("SELECT * FROM Login WHERE Empid = '" & TextBox1.Text & "' AND password = '" & TextBox2.Text & "' , con")

cmd = New OleDb.OleDbCommand("SELECT * FROM Login WHERE Empid = '" & TextBox1.Text & "' AND password = '" & TextBox2.Text & "'" , con)

(差异在最后)