2010-07-24 54 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