我的代码没有显示任何记录,这可能是什么问题 或者是否可以在按钮上显示记录?
Imports MySql.Data.MySqlClient
Public Class Form4
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As New MySqlConnection
If con.State = ConnectionState.Closed Then
con.ConnectionString = "server=localhost;user id=root;database=db"
con.Open()
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sql As String = "SELECT * FROM candidate"
Dim con As MySqlConnection = New MySqlConnection
Dim cmd As MySqlCommand = New MySqlCommand(sql, con)
con.Open()
Dim dr As MySqlDataReader = cmd.ExecuteReader
While dr.Read
Button1.Text = dr.GetValue(0).ToString
End While
dr.Close()
con.Close()
End Sub
End Class
答案 0 :(得分:1)
您在Button1_Click
方法中初始化的连接对象似乎没有提供任何连接字符串。我担心你提供的代码会出现异常。
答案 1 :(得分:0)
不要让连接以这种方式挂起,特别是MySql。 删除表单加载中无用的连接创建,并仅使用相应的连接字符串单击按钮创建连接
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sql As String = "SELECT * FROM candidate"
Using con = New MySqlConnection("server=localhost;user id=root;database=db")
Using cmd = New MySqlCommand(sql, con)
con.Open()
Using dr = cmd.ExecuteReader
While dr.Read
Button1.Text = dr.GetValue(0).ToString
End While
End Using
End Using
End Using
End Sub
Using语句将防止丢失有价值的资源,例如连接,命令和datareader,因为这些对象将被关闭并立即处理在结束时使用行也可以在异常的情况下使用
作为旁注,您的代码将在按钮中显示从候选表中提取的最后一个值,因为在您的reader.Read循环中,您继续为当前记录的值分配按钮文本,直到您到达最后一个记录。所以可能有一些东西需要重新考虑