我要做的是保持MySQL连接从Window1(LoginWindow)打开到Window2(DBAA)。这样在第二个窗口中我就可以读取和插入数据。当我尝试插入数据时,我得到了#34; Host不允许连接到这个MySQL服务器"
Imports MySql.Data.MySqlClient
Public Class LoginWindow
Dim MysqlConn As MySqlConnection
Public Sub Button_Click(sender As Object, e As RoutedEventArgs)
MysqlConn = New MySqlConnection()
MysqlConn.ConnectionString = "server=" & server.Text & ";" _
& "user id=" & username.Text & ";" _
& "password=" & password.Password & ";" _
& "database=" & database.Text & ";"
Try
MysqlConn.Open()
MessageBox.Show("Connection to Database has been opened.")
Catch myerror As MySqlException
MessageBox.Show("Cannot connect to database: " & myerror.Message)
Finally
MysqlConn.Dispose()
End Try
Dim DBAA As DBAA = New DBAA
DBAA.Show()
Me.Hide()
End Sub
//Non Applicable Code
End Class
这是打开的第二个窗口(DBAA)。
Imports MySql.Data.MySqlClient
Imports System.Data.Sql
Public Class DBAA
Dim con As New MySqlConnection
Dim result As Integer
Dim cmd As New MySqlCommand
Private Sub insert01_Click_1(sender As Object, e As RoutedEventArgs) Handles insert01.Click
Try
con.Open()
With cmd
.Connection = con
.CommandText = "INSERT INTO `test`.`data` (`value1`) " & _
"VALUES ('" & data01.Text & "');"
result = cmd.ExecuteNonQuery
If result = 0 Then
MsgBox("Success!")
End If
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
End Class
答案 0 :(得分:0)
在您的第二个代码中,您定义了连接,但遗漏了您的连接信息。您需要提供连接详细信息。你打电话给.Open连接,但它没有你的连接信息。
也不要保持开放,根本不是好的做法。你关闭它的第一个代码很好,但是你的第二个代码遗漏了一些细节。
编辑...
如果你想传递连接,你可以在构造函数中这样做......
确保你在第二节课中有这个......
Private Property connection As MySqlConnection
Public Sub New(ByVal con as MySqlConnection)
connection = con
End Sub
现在您可以使用'连接'你想要的地方......
然后你将当前连接作为第二个类的参数传递...
Dim DBAA As DBAA = New DBAA(MysqlConn)