首页 > 解决方案 > 连接字符串属性尚未初始化

问题描述

所以我试图根据我的组合框填充我的文本框,该组合框也链接在我的 sql 服务器中。

每次我在 ComboBox 中选择一个项目时都会出现此错误。

连接字符串属性尚未初始化

    Private Sub CBuname_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CBuname.SelectedIndexChanged
    Dim cmd As New SqlCommand()
    Dim Reader As SqlDataReader
    Try
        con.Open()
        Dim sql As String = "Select * From CoAdminData where Username='" & CBuname.Text & "'"
        cmd = New SqlCommand(sql, con)
        Reader = cmd.ExecuteReader

        If Reader.HasRows() Then
            While Reader.Read
                txtSID.Text = Reader("StudentID")
                txtFirstname.Text = Reader("Firstname")
                txtLastname.Text = Reader("Lastname")
            End While
        End If
        con.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        con.Dispose()
    End Try

End Sub

标签: sql-servervb.net

解决方案


只是为了给出一个完整的示例和模板,您可以使用/修改。我已经评论了你需要开始的一切。
与其在公共类中声明 con,不如尝试使用每个方法打开和关闭它。您可以在其他地方公开声明 constr,这样可以节省一些写作时间。Hth

Imports System.Data.SqlClient 

Private Sub Template_SQL_Reader()
    'Obviously rename SQL with you server, DATABASE with the DB, USERNAME and PASSWORD with your creds too
    Dim constr As String = "Server=SQL;Initial Catalog=DATABASE;uid=USERNAME;Pwd='Password'"
    Dim con As SqlConnection = New SqlConnection(constr)

    'Carefull not to include query string that could allow
    'SQL injection (https://en.wikipedia.org/wiki/SQL_injection)
    Dim qry As String = "SELECT * FROM TABLE" '<<< Ok - No SQL Injection avaliable
    'Dim qry As String = "SELECT * FROM TABLE WHERE FirstName='" & textbox1.text & "'" <<< BAD IDEA SQL Injection Possible !!!!!!
    Dim cmd As SqlCommand = New SqlCommand(qry, con)

    'Open connection
    con.Open()
    Dim rdr As SqlDataReader = cmd.ExecuteReader

    While rdr.Read
        'If there are no rows - then nothing will happen, as .read = false
        'Do your reading...
    End While

    'Dispose command
    cmd.Dispose()
    'close connection
    con.Close()
End Sub

推荐阅读