gpt4 book ai didi

mysql - Mysql 类中未处理的异常

转载 作者:行者123 更新时间:2023-11-29 13:21:32 24 4
gpt4 key购买 nike

我正在尝试创建一个 vb.net 类来管理 MySQL 数据库连接,并且我有一个 Connect 方法,该方法应该将连接字符串分配给 mysqlconnection 变量,但我总是收到错误:

An unhandled exception of type 'System.NullReferenceException' occurred in Projecto_Aula.exe Additional information: Object reference not set to an instance of an object.

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

最佳答案

所有这些都未设置(空/无):

Private sqlReader As MySqlDataReader
Private sqlAdapter As MySqlDataAdapter
Private sqlCommand As MySqlCommand
Private sqlConnection As MySqlConnection

您需要在使用 then 之前创建对象:

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

关于mysql - Mysql 类中未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20774709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com