这个问题在这里已经有答案了:
什么是nullreferenceexception,如何修复它(28个答案)
两年前关门了。
我有两组函数,它们的工作原理是相似的,但第二组使用的是结构。我正在尝试使用结构设置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条答案
按热度按时间jhiyze9q1#
你的代码中有一个问题,就是错误所说的。你想用
Connection
没有初始化它。所以初始化struct变量如下: