Imports MySql.Data.MySqlClient
Public Class Form1
Dim ServerString As String = "Server=localhost;User Id=root;Password=root;Database=youtube"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
MsgBox("YAY! you are now connected")
Else
MsgBox("LOL Nope! you are not connected")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Form1_Unload(sender As Object, e As EventArgs) Handles MyBase.FormClosing
SQLConnection.Close()
SQLConnection.Dispose()
End Sub
Public Sub SaveNames(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery() // keeps on saying System.InvalidOperationException: 'Connection must be valid and open.'
End With
SQLConnection.Close()
MsgBox("YAY, you are now connected")
SQLConnection.Dispose()
End Sub
Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
Dim SQLStatement As String = "INSERT INTO people(name) VALUES ('" & txtName.Text & "')"
SaveNames(SQLStatement)
End Sub
End Class
答案 0 :(得分:0)
Imports MySql.Data.MySqlClient
Public Class Form1
Dim ServerString As String = "Server=localhost;User Id=root;Password=root;Database=youtube"
Dim SQLConnection As MySqlConnection(ServerString)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
SQLConnection.Open()
If SQLConnection.State != ConnectionState.Closed Then
MsgBox("LOL Nope! you are not connected")
Else
MsgBox("YAY! you are now connected")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
SQLConnection.Close()
SQLConnection.Dispose()
End Sub
Public Sub SaveNames(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand(SQLStatement,SQLConnection)
cmd.ExecuteNonQuery()
MsgBox("YAY, you are now connected")
SQLConnection.Close()
SQLConnection.Dispose()
End Sub
Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
Dim SQLStatement As String = "INSERT INTO people(name) VALUES ('" & txtName.Text & "')"
SaveNames(SQLStatement)
End Sub
End Class
尝试一下,让我知道它是否有效,我没有测试它但它应该工作。 您希望在进行调用的方法中打开和关闭连接。 您不希望在表单首次加载时打开连接,然后将其保持打开状态直到表单关闭,这是一种不好的做法。
另请参阅使用数据库访问时,这将关闭并处理您的连接而无需添加代码。 https://docs.microsoft.com/en-us/dotnet/articles/visual-basic/language-reference/statements/using-statement
在控制台应用程序而不是WinForm应用程序中尝试它,这将在添加UI问题之前从示例中获得一些复杂性。