我是Visual Basic的新手,现在我将我的程序连接到数据库以保存并获取输入,并且工作正常。我现在想要做的是在其他表单上重用我与数据库的连接。我正在考虑接受全球宣言并把它们放到一个班级并让它们可以从那里访问,但我不知道该怎么做。我尝试了不同的方法,但我总是遇到一些错误...我真的被困住了,并且会感激我能得到的任何帮助。
以下是代码的一部分:
Imports MySql.Data.MySqlClient
Public Class Form1
'GLOBAL DELARATION
Dim conString As String = "Server=localhost;" & "Database=data;" & "Uid=password;" & "Pwd=password;"
Dim con As New MySqlConnection(conString)
Dim cmd As MySqlCommand
Dim adapter As MySqlDataAdapter
Dim dt As New DataTable()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'CONSTRUCT DATAGRID VIEW
DataGridView1.ColumnCount = 4
DataGridView1.Columns(0).Name = "ID"
DataGridView1.Columns(1).Name = "Name"
DataGridView1.Columns(2).Name = "Position"
DataGridView1.Columns(3).Name = "TEAM"
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
Retrieve()
End Sub
Private Sub cleartxt()
TextBox_name.Text = ""
TextBox_position.Text = ""
TextBox_team.Text = ""
End Sub
'INSERT INTO DB
Private Sub Add()
Dim sql As String = "INSERT INTO people(Name,Position,Team) VALUES(@NAME,@POSITION,@TEAM)"
cmd = New MySqlCommand(sql, con)
'PARAMETERS
cmd.Parameters.AddWithValue("@NAME", TextBox_name.Text)
cmd.Parameters.AddWithValue("@POSITION", TextBox_position.Text)
cmd.Parameters.AddWithValue("@TEAM", TextBox_team.Text)
'Open Connection and INSERT
Try
con.Open()
If cmd.ExecuteNonQuery() > 0 Then
MsgBox("Produktet er lagt inn korrekt")
cleartxt()
End If
con.Close()
Retrieve()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub