2010-07-24 31 views
1

请帮忙,我如何真正在vb.net中使用数据读取器。我使用odbc来连接mysql和vb.net。
功能I模块上宣称:如何在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 

text_changed事件:

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 

我看到的结果,但它只能装载数据库上的第一个项目。我已经把这段代码放入了text_changed事件中。这样做的正确方法是什么?第二个代码有什么问题,为什么它只加载第一个数据

正如你所看到的con是我声明函数的模块。然后我在表单中创建了一个对象。

回答

2

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") 
0

你只是把数据读取器的对象,而loop.Here是示例代码:

 dr = myCommand.ExecuteReader() 
     While dr.Read() 
     'reading from the datareader 
     MessageBox.Show("colname1" & dr(0).ToString()) 
     MessageBox.Show("colname2" & dr(1).ToString()) 
     MessageBox.Show("colname3" & dr(2).ToString()) 
     MessageBox.Show("colname4" & dr(3).ToString()) 
     MessageBox.Show("colname5" & dr(4).ToString()) 
     'displaying the data from the table 
     End While 
     dr.Close() 
+0

另一个复制粘贴 – user225269 2010-07-24 12:37:25