gpt4 book ai didi

mysql - 将 Class1.vb 中声明的 "all"变量访问到 vb.net 中解决方案的多种形式

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

经过一系列下载连接器和一些插件后,我终于成功将 xampp 连接到 VB.Net。虽然我发现每次将连接字符串放入需要 SQL insert 和 select 语句的每个表单时都非常耗时/麻烦,所以我想出了创建 Class1.vb 并将所有内容放在那里的想法xampp 的连接字符串。因此,每次我创建新表单时,我所要做的就是将 Class1.vb 导入到每个表单中,以便我可以访问 Dim conn As New MySqlConnection ,因为我已经提到在 Class1.vb

上声明

但是,不知何故,我与MYSQL连接,大多数变量(包括带有dbtable名称的变量)都无法访问。让我向您展示我的 Class1.vb

里面有什么
Public Class Class1
Dim conn As New MySqlConnection
Dim command As MySqlCommand
Dim reader As MySqlDataReader

Public Sub mysqlConnect()

If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format('connectionString for Dbname,server,uid,pword)
Try
conn.Open()

MessageBox.Show("Connected!")
Catch x As Exception
MsgBox(x.Message)
End Try
conn.Close()
end sub
end class

Form1.vb 内部

Public Class Form1
Dim newCon as New Class1


Private Sub Form2_Load
newCon.mysqlConnect()
'Note: mysqlConnect() is a function declared in Class1.vb


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
conn.Open()
Catch x As Exception
End Try
Dim command As New MySqlCommand(String.Format("INSERT STATEMENT"))
command.ExecuteNonQuery()
conn.Close()
End Sub

但是我在 Button1_Click 上指示的变量不起作用。就好像无法读取 Public Sub Connect() 的某些函数不过,正如我之前提到的,Msgbox("Connected") 确实有效,这意味着我与我的 DB 完全连接。

friend 们,有什么想法吗?

感谢您的评论。提前致谢。

最佳答案

两种常见的解决方案是:1) 将您的 Class1 更改为具有“工厂方法”,这将为您提供开放的连接。2)将你的连接包装在你的类中

示例1:

Public Class Class1
Dim conn As New MySqlConnection
Dim command As MySqlCommand
Dim reader As MySqlDataReader


Public Shared Function mysqlConnect() AS MySqlConnection

If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format('connectionString for Dbname,server,uid,pword')
Try
conn.Open()

''MessageBox.Show("Connected!")
Catch x As Exception
MsgBox(x.Message)
End Try
''conn.Close() ''This must be done by your calling function now
''btw, if you forget, it may cause connection leaks, which are evil
Return conn
End function
End class

示例2:

Public Class Class1
Public conn As MySqlConnection
Dim command As MySqlCommand
Dim reader As MySqlDataReader

''open the connection in the constructor
Sub New()
conn = New MySqlConnection
conn.ConnectionString = String.Format('connectionString for Dbname,server,uid,pword')
Try
conn.Open()

''MessageBox.Show("Connected!")
Catch x As Exception
MsgBox(x.Message)
End Try
End Sub

''close the connection in the destructor
Protected Overrides Sub Finalize()
conn.Close() ''automatically runs when this class is garbage collected
conn.Dispose()
End Sub
End class

关于mysql - 将 Class1.vb 中声明的 "all"变量访问到 vb.net 中解决方案的多种形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36176112/

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