我正在尝试创建一个vb.net类来管理MySQL数据库连接,我有一个方法Connect,它将连接字符串分配给mysqlconnection变量,但我总是得到错误:
未处理的类型' System.NullReferenceException' 发生在Projecto_Aula.exe中的附加信息:对象引用 没有设置为对象的实例。
DatabaseManager.vb
Imports MySql.Data.MySqlClient
Public Class DatabaseManager
Private connetionString As String = vbNullString
Private sqlReader As MySqlDataReader
Private sqlAdapter As MySqlDataAdapter
Private sqlCommand As MySqlCommand
Private sqlConnection As MySqlConnection
Sub New(ByVal host As String, ByVal user As String, ByVal password As String, Optional ByVal database As String = "requisicoes")
connetionString = "server=" & host & "; uid=" & user & "; pwd=" & password & "; database=" & database
MsgBox(connetionString)
End Sub
Public Sub Connect()
If (sqlConnection.State = ConnectionState.Open) Then ''throws exception when run
MsgBox("Already connected to the database.")
Return
End If
sqlConnection.ConnectionString = connetionString.ToString()
If (connetionString = vbNullString) Then
MsgBox("Invalid Connection String!")
Application.Exit()
End If
Try
sqlConnection.Open()
Catch ex As MySqlException
MsgBox("Error connecting: " & ex.ToString())
Application.Exit()
End Try
End Sub
End Class
MainMenu.vb
Public Class Login
Public databaseManager As New DatabaseManager("localhost", "root", "", "requisicoes")
Private Sub Form1_Load_1(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
databaseManager.Connect() 'throws exception when run
End Sub
End Class
答案 0 :(得分:1)
所有这些都没有设置(null / Nothing):
Private sqlReader As MySqlDataReader
Private sqlAdapter As MySqlDataAdapter
Private sqlCommand As MySqlCommand
Private sqlConnection As MySqlConnection
您需要在使用之前创建对象:
Me.sqlReader = New MySqlDataReader
Me.sqlAdapter = New MySqlDataAdapter
Me.sqlCommand = New MySqlCommand
Me.sqlConnection = New MySqlConnection
所以在Connect()
方法中创建一个新的MySqlConnection
并用有效的连接字符串替换“myConnectionString”。
Public Sub Connect()
Me.sqlConnection = New MySqlConnection("myConnectionString")
Try
Me.sqlConnection.Open()
MsgBox(Me.sqlConnection.State.ToString())
Catch ex As MySqlException
MsgBox("Error connecting: " & ex.ToString())
Application.Exit()
End Try
End Sub
答案 1 :(得分:0)
使用此提及代码
更改以下代码行 sqlConnection.ConnectionString = connetionString.ToString()
更改为:
sqlConnection.ConnectionString = Convert.ToString(connetionString)