1

我有一个按钮检索我只想通过其行和列获取数据库表“帐户”值并将其显示在文本框中。我不断在数据填充线上遇到错误

 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
4

1 回答 1

0

您需要实例化传递给 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

请参阅使用语句

但是,如果您只需要一行,最好使用 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

这希望将只返回所需的行

于 2013-05-17T23:26:17.057 回答