【问题标题】:"The ConnectionString property has not been initialized" error in VB.NETVB.NET 中的“ConnectionString 属性尚未初始化”错误
【发布时间】:2012-02-06 15:38:55
【问题描述】:

每次我尝试连接到数据库时,它都会给我这个错误“The ConnectionString property has not been initialized”

我能做些什么来解决这个问题?

这是我的代码

Module Module1
    Function GetInfoForStudent(ByRef QueryName As String, ByVal UserName As String, ByVal Password As String) As DataTable
        Using Con As New SqlConnection
            Try
                Using OleCon As New SqlConnection
                    Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library
Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
                    Con.Open()
                    Dim Cmd As SqlCommand = Con.CreateCommand()
                    Cmd.CommandType = CommandType.StoredProcedure
                    Cmd.CommandText = QueryName
                    Cmd.Parameters.AddWithValue("@user", UserName)
                    Cmd.Parameters.AddWithValue("@pass", Password)
                    Dim da As New SqlDataAdapter(Cmd)
                    Dim ds As New DataTable()
                    da.Fill(ds)
                    Return ds
                End Using
            Catch ex As Exception

                Throw New Exception(ex.Message)
            End Try
        End Using

    End Function

End Module

Sub ShowStudentInfo()
    Dim dt As DataTable = GetInfoForStudent("MyStoredProcName", "@user", "@pass")
    ' Since (presumably) only one is returned
    With dt.Rows(0)
        ' Assign your text boxes 
        StudentIDTextBox.Text = .Item("StudentID")
        LoginIDTextBox.Text = .Item("LoginID")
        Student_NameTextBox.Text = .Item("Student Name")
        Student_addressTextBox.Text = .Item("Student address")

    End With
End Sub

【问题讨论】:

    标签: database vb.net sql-server-2008 connection-string


    【解决方案1】:

    您从未将连接字符串分配给连接对象,就像错误所说的那样。

    在 con.open 之前插入一行设置连接字符串。

    Con.connectionstring = connection
    Con.Open()
    

    或者更好的是,将您的 using 语句更改如下

    Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library Catalog System\Library Catalog System\library.mdf;Integrated
    Security=True;Connect Timeout=30;User Instance=True"
    
    Using Con As New SqlConnection(connection)
    

    【讨论】:

    • 您可能还会查看“OleCon”代码,似乎没有必要,因为您从未使用过该变量。顺便说一句:我需要的所有感谢都是赞成票。
    • 好的,我更改了声明,再次感谢。尽管我想给你一个支持,但我仍然缺乏声誉。但我真的很感谢你的帮助,祝你有美好的一天。
    • @CompleteNewb 如果 JohnFx 的回答有帮助,那么选择就是您的回答(他的帖子旁边的复选标记)。这也会给你 2 声望。
    【解决方案2】:

    您正在创建连接字符串对象,但从未将其分配给您的 SqlCommand 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多