ConnectionString属性尚未初始化。 VB.Net

时间:2016-04-20 19:11:45

标签: sql vb.net connection-string

我有以下代码:

            Dim command As New SqlCommand

        command.Parameters.AddWithValue("@customerid", textbox1.text)
        command.Parameters.AddWithValue("@password", textbox2.text)

        command .Connection = SharedVar.ConnectionString
        SharedVar.ConnectionString.Open()
        command .CommandText = ("SELECT Customer FROM Accounts WHERE CustomerID = @customerid AND Password = @password")

当我执行代码时,我在这个位置出错:

SharedVar.ConnectionString.Open()

我收到的错误是:ConnectionString属性尚未初始化。

SharedVar是一个模块,在这个模块中有一个名为ConnectionString的变量。 ConnectionString声明为SQLConnection。连接字符串本身保存在application.settings中。 SharedVar.ConnectionString的代码是:

    Public ConnectionString As New SqlConnection(My.Settings.ConnectionString)

我不知道为什么我收到此错误,因为我已在声明ConnectionString属性:

command .Connection = SharedVar.ConnectionString

My.Settings.ConnectionString保存的连接字符串是:

Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Nico\Documents\Visual Studio 2015\Database\CustomerDatabase.mdf;Integrated Security=True

我感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可能需要重新评估变量命名,因为它可能有些令人困惑。您当前的代码将实际的SqlConnection对象实例化为ConnectionString(而不仅仅是连接字符串本身,它是String):

' This creates an actual connection. (My.Settings.ConnectionString is '
' your connnection string) '                                           
Public ConnectionString As New SqlConnection(My.Settings.ConnectionString)

在构建查询时,请考虑使用类似以下的模式:

' Build your connection '
Using connection As New SqlConnection(My.Settings.ConnectionString)
    ' Create your query '
    Dim query = "SELECT Customer FROM Accounts WHERE CustomerID = @customerid AND Password = @password"
    ' Build a command to execute '
    Using command As New SqlCommand(query, connection)
         ' Open your connection '
         connection.Open()
         ' Add your parameters ' 
         command.Parameters.AddWithValue("@customerid", textbox1.Text)
         command.Parameters.AddWithValue("@password", textbox2.Text)
         ' Execute your query into a reader '
         Using reader = command.ExecuteReader()
               While reader.Read()
                    ' Access your custom information here '
                    Dim customer = reader("Customer")
                    ' Do something else here ... '
               End While
         End Using
    End Using
End Using

此外,如果没有看到整个代码片段,很难准确确定何时设置了某些属性。这可能只是在调用Open()方法之前未在Connection上设置连接字符串的实例。