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

时间:2013-05-17 23:17:24

标签: mysql database vb.net

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

 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

1 个答案:

答案 0 :(得分: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

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

希望这将只返回所需的行