请帮助,我如何在vb.net中真正使用数据阅读器。我用odbc连接mysql和vb.net。
在模块上声明的函数:

Public Function form2search(ByVal drugname As String) As OdbcDataReader

        cmd.CommandText = "SELECT *  FROM drug WHERE Drug_name LIKE'%" & drugname & "' "
        Return cmd.ExecuteReader

    End Function

文本更改事件:
con.drugname=textBoxdrugname.text
     Dim rdr As Odbc.OdbcDataReader
            rdr = con.form2search(drugname)
        if rdr.hasrows=true then
        rdr.read()

        TextBoxdrugname.Text = rdr("Drug_name").ToString
                        TextBoxdrugcode.Text = rdr("Drug_code").ToString
                        drugtype.Text = rdr("Drug_type").ToString

        end if

我看到一个结果,但它只加载数据库中的第一项。我已将此代码放入文本更改事件中。做这件事的正确方法是什么?第二个代码有什么问题,为什么它只加载第一个数据
如你所见,con是我声明函数的模块。然后我在表单中创建了一个对象。

最佳答案

DataReader是一个低级实现,不支持导航,每次调用时只读取一行

reader.Read()

对于windows窗体应用程序,您可能应该使用dataset/datatable方法或orm。您应该考虑在odbc驱动程序上使用mysql连接器网络。它可以在mysql.com上找到。
下面是一些演示代码:
dim table as new DataTable("table1")

' Create a Connection
using conn as new MysqlConnection("...connectionstring")
    conn.Open() ' Open it

    ' Create a new Command Object
    using cmd as new MysqlCommand("SELECT * FROM table", conn)

        ' Create a DataAdapter
        ' A DataAdapter can fill a DataSet or DataTable
        ' and if you use it with a CommandBuilder it also
        ' can persist the changes back to the DB with da.Update(...)
        using da as new MysqlDataAdapter(cmd)
            da.Fill(table) ' Fill the table
        end using

    end using
end using

' A Binding Source allows record navigation
dim bs as new BindingSource(table, nothing)

' You can bind virtually every property (most common are "text" "checked" or "visible"
' of a windows.forms control to a DataSource
' like a DataTable or even plain objects
textBox1.DataBindings.Add("Text", bs, "columnName")

' Now you can navigate your data
bs.MoveNext()

' Even a ComboBox can be bound to a List and display the related value
' of your current row
comboBox1.DataSource = table2
comboBox1.DisplayMember = "name"
comboBox1.ValueMember = "id"

comboBox1.DataBindings.Add("SelectedValue", bs, "id")

关于mysql - 如何在vb.net中使用数据读取器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3324425/

10-11 15:05
查看更多