How to Get Field Value Using Data Reader
Submitted by GeePee on Thursday, May 28, 2015 - 23:50.
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.
To call this function, issue this command:
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.
- Public Function GetFieldValue(ByVal srcSQL As String, ByVal strField As String)
- Dim conn As New OleDb.OleDbConnection(My.Settings.DataConnectionString)
- Try
- conn.Open()
- Dim cmd As OleDbCommand = New OleDbCommand(srcSQL, conn)
- 'create data reader
- Dim rdr As OleDbDataReader = cmd.ExecuteReader
- 'loop through result set
- rdr.Read()
- If rdr.HasRows Then GetFieldValue = rdr(strField).ToString()
- 'close data reader
- Catch ex As Exception
- MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
- End Try
- End Function
- Dim strValue as String
- strValue = GetFieldValue("SELECT * FROM Table1 WHERE ID = 1", "Field1")
Add new comment
- 302 views