vb.net查询mysql数据库完整代码
时间: 2023-08-12 12:59:04 浏览: 331
下面是一个简单的VB.NET代码示例,演示如何连接到MySQL数据库并执行查询:
```vb
Imports System.Data
Imports MySql.Data.MySqlClient
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' MySQL数据库连接字符串
Dim connectionString As String = "server=<server>;port=<port>;user=<username>;password=<password>;database=<database>"
' 创建连接对象
Using connection As New MySqlConnection(connectionString)
Try
' 打开数据库连接
connection.Open()
' 创建查询命令
Dim query As String = "SELECT * FROM your_table"
Dim command As New MySqlCommand(query, connection)
' 执行查询并获取结果集
Dim reader As MySqlDataReader = command.ExecuteReader()
' 遍历结果集并输出数据
While reader.Read()
Dim id As Integer = reader.GetInt32("id")
Dim name As String = reader.GetString("name")
Dim age As Integer = reader.GetInt32("age")
Console.WriteLine("ID: " & id & ", Name: " & name & ", Age: " & age)
End While
' 关闭数据阅读器
reader.Close()
Catch ex As Exception
' 处理异常
Console.WriteLine("Error: " & ex.Message)
Finally
' 关闭数据库连接
connection.Close()
End Try
End Using
End Sub
End Class
```
请注意,你需要将`<server>`、`<port>`、`<username>`、`<password>`和`<database>`替换为你的MySQL数据库的实际连接信息。此示例仅用于演示目的,实际情况中你可能需要根据自己的需求进行更多的错误处理和结果处理。
阅读全文