How to Get Field Value Using Data Reader

Using a DataReader to get a value from a database table is the fastest way compare to other method. DataReader directly accesses database record using ExecuteReader Function. Here’s a function that will get the data using a DataReader.
  1. Public Function GetFieldValue(ByVal srcSQL As String, ByVal strField As String)
  2. Dim conn As New OleDb.OleDbConnection(My.Settings.DataConnectionString)
  3.  
  4. Try
  5. conn.Open()
  6.  
  7. Dim cmd As OleDbCommand = New OleDbCommand(srcSQL, conn)
  8. 'create data reader
  9. Dim rdr As OleDbDataReader = cmd.ExecuteReader
  10.  
  11. 'loop through result set
  12. rdr.Read()
  13.  
  14. If rdr.HasRows Then GetFieldValue = rdr(strField).ToString()
  15.  
  16. 'close data reader
  17. conn.Close()
  18. Catch ex As Exception
  19. MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  20. End Try
  21. End Function
To call this function, issue this command:
  1. Dim strValue as String
  2.  
  3. strValue = GetFieldValue("SELECT * FROM Table1 WHERE ID = 1", "Field1")
Where Table1 is the name of your table, and Field1 is the name of the field that you want to get value. Another method is DataSet. It can also access database record but it pulls all the database schema together with its data. We will discuss DataSet in our next tutorial.

Tags

Add new comment