将连接字符串分配给结构的MySQL连接属性时发生NullReferenceException错误

时间:2018-08-24 15:23:56

标签: mysql vb.net

这就是问题,我有两组应该以相似的方式工作的功能,但是第二组使用结构。我正在尝试使用结构设置mysql连接。第一个有效,它使用在另一个模块中声明的公共变量。第二个没有,它使用在另一个模块中声明为public的结构。设置ConnectionString属性时,它总是会给我NullReferenceException。

第一(工作中)

Public Function CheckConnection(server As String, port As String, username As String, password As String) As Boolean
    Try
        sqlConnection.ConnectionString = BuildConnectionString(server, port, username, password)
        sqlConnection.Open()
        Return True
    Catch ex As Exception
        Return False
    Finally
        If Not sqlDataReader Is Nothing Then sqlDataReader.Close()
        If sqlConnection.State = ConnectionState.Open Then sqlConnection.Close()
    End Try        
End Function

第二(不起作用)

Public Function CheckConnection(server As String, port As String, username As String, password As String) As Boolean

    Try
        Dim structQuery As New MyQueryStructure
        With structQuery
            .Server = server
            .Port = port
            .Username = username
            .Password = password
            .Connection.ConnectionString = BuildConnectionString(.Server, .Port, .Username, .Password)
        End With
        structQuery.Connection.Open()
        Return True
    Catch ex As Exception
        GenerateErrorReport(ex)
        Return False
    End Try

End Function

其他代码和变量

Public Function BuildConnectionString(stringHost As String, stringPort As String, stringUsername As String, stringPassword As String)
    Return "Server=" & stringHost & ";Port=" & stringPort & ";Uid=" & stringUsername & ";Pwd=" & stringPassword & ";Allow User Variables=True;Persist Security Info=true;SslMode=none;"
End Function

Public sqlConnection As New MySqlConnection
Public sqlQuery As String
Public sqlCommand As New MySqlCommand
Public sqlDataReader As MySqlDataReader
Public sqlDataAdapter As New MySqlDataAdapter
Public sqlDataset As New DataSet
Public sqlDataTable As New DataTable
Public sqlServer, sqlPort, sqlUsername, sqlPassword As String

Public Structure MyQueryStructure
    Dim Connection As MySqlConnection
    Dim Command As MySqlCommand
    Dim DataReader As MySqlDataReader
    Dim DataAdapter As MySqlDataAdapter
    Dim DataSet As DataSet
    Dim DataTablee As DataTable
    Dim Line As String
    Dim Server As String
    Dim Port As String
    Dim Username As String
    Dim Password As String
End Structure

我总是可以回到第一个。但是我有点想学习如何使用结构。另外,我需要在运行时更改连接字符串。

1 个答案:

答案 0 :(得分:1)

您的代码中确实有错误提示的问题。您试图使用Connection而不进行初始化。因此,像这样初始化您的struct变量:

With structQuery
    .Server = server
    .Port = port
    .Username = username
    .Password = password
    .Connection = New MySqlConnection(BuildConnectionString(.Server, .Port, .Username, .Password))
End With