VB连接MySQL数据库源码是一段用Visual Basic编写的代码,用于连接和操作MySQL数据库。下面是一个示例代码:
Imports MySql.Data.MySqlClient
Public Class Form1
Dim conn As MySqlConnection
Dim cmd As MySqlCommand
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'连接MySQL数据库
conn = New MySqlConnection("server=数据库服务器地址;user id=用户名;password=密码;database=数据库名")
Try
conn.Open()
MessageBox.Show("连接成功")
Catch ex As Exception
MessageBox.Show("连接失败:" & ex.Message)
End Try
End Sub
Private Sub btnInsert_Click(sender As Object, e As EventArgs) Handles btnInsert.Click
'向数据库插入数据
Dim sql As String = "INSERT INTO 表名 (字段1, 字段2) VALUES (@value1, @value2)"
cmd = New MySqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@value1", txtValue1.Text)
cmd.Parameters.AddWithValue("@value2", txtValue2.Text)
Try
cmd.ExecuteNonQuery()
MessageBox.Show("插入成功")
Catch ex As Exception
MessageBox.Show("插入失败:" & ex.Message)
End Try
End Sub
Private Sub btnQuery_Click(sender As Object, e As EventArgs) Handles btnQuery.Click
'从数据库查询数据
Dim sql As String = "SELECT * FROM 表名"
cmd = New MySqlCommand(sql, conn)
Dim reader As MySqlDataReader
Try
reader = cmd.ExecuteReader()
While reader.Read()
'处理查询结果
Dim value1 As String = reader.GetString("字段1")
Dim value2 As String = reader.GetString("字段2")
MessageBox.Show("字段1: " & value1 & ", 字段2: " & value2)
End While
Catch ex As Exception
MessageBox.Show("查询失败:" & ex.Message)
End Try
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
'关闭数据库连接
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Sub
End Class
这段代码实现了以下功能:
这段代码使用了MySql.Data.MySqlClient命名空间中的类来连接和操作MySQL数据库。在使用该代码之前,需要先安装MySQL Connector/NET,该组件可以从MySQL官网下载安装。
此外,该代码还需要根据实际情况修改数据库服务器地址、用户名、密码、数据库名、表名和字段名。
推荐的腾讯云相关产品:
这些产品能够满足云计算领域的数据库和服务器需求。
领取专属 10元无门槛券
手把手带您无忧上云