使用vb 2012从mysql获取特定的行列值

fkaflof6  于 2022-12-26  发布在  Mysql
关注(0)|答案(1)|浏览(100)

我有一个按钮检索我只是想得到数据库表“帐户”的值由其行和列,并显示在一个文本框中。我不断得到错误的数据填充行

Imports MySql.Data.MySqlClient
Public Class Form1
Dim dataset As DataSet
Dim datatable As DataTable
Dim sqlcon As MySqlConnection
Dim dataadapter As MySqlDataAdapter
Dim sqlcommand As MySqlCommand
Dim sql As String

Private Sub retrieve_Click(sender As Object, e As EventArgs) Handles retrieve.Click

    sqlcon = New MySqlConnection("Data Source=localhost;Database=database;User ID=root;Password=;")

        sqlcon.Open()

    sql = "select * from account"
    dataadapter = New MySqlDataAdapter(sql, sqlcon)
    dataadapter.Fill(dataset)
    TextBox2.Text = dataset.Tables(0).Rows(0).Item(0).ToString()
End Sub
End Class
huwehgph

huwehgph1#

您需要示例化传递给Fill方法的数据集。

....
dataset = new DataSet()
dataadapter.Fill(dataset)
...

完成后不要忘记关闭连接。在不需要时保持连接是一项非常昂贵的资源

Using sqlcon = New MySqlConnection("Data Source=localhost;Database=database;User ID=root;Password=;")

    sqlcon.Open()
    sql = "select * from account"
    dataadapter = New MySqlDataAdapter(sql, sqlcon)
    dataset = new DataSet()
    dataadapter.Fill(dataset)
    TextBox2.Text = dataset.Tables(0).Rows(0).Item(0).ToString()
End Using

See the Using Statement
但是,如果您只需要一行,则最好应用WHERE子句来限制数据库返回的结果,从而优化查询。

sql = "select * from account WHERE AccountName = @name"
    dataadapter = New MySqlDataAdapter(sql, sqlcon)
    dataadapter.SelectCommand.Parameters.AddWWithValue("@name", inputNameBox.Text)
    dataset = new DataSet()
    dataadapter.Fill(dataset, "Account")
    if dataset.Tables("Account").Rows.Count > 0 then 
        TextBox2.Text = dataset.Tables("Account").Rows(0).Item(0).ToString()
    End If

这有望只返回所需的行

相关问题