Oracle Database Interaction Using ODP.NET and ASP.NET: All Ways to Retrieve Data - Getting a single value from the database
(Page 5 of 5 )
Let us consider the following example:
Dim cn As New OracleConnection("User ID=scott;password=tiger;Data
Source=ORCL")
Try
Dim cmd As New OracleCommand("select count(*) from
emp", cn)
cmd.Connection.Open()
Me.lblError.Text = "No. of rows " & cmd.ExecuteScalar
cmd.Dispose()
Catch ex As Exception
Me.lblError.Text = ex.Message
Finally
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
In the above example, I simplified the code by removing repeated steps. Instead I tried to mix a larger number of statements within a single statement. In the above example, our main concentration should be on the following line:
Me.lblError.Text = "No. of rows " & cmd.ExecuteScalar
First of all, consider my apologies that I assigned the value to the “label” control, which is actually dedicated to showing error messages. I just did this, as it is a simple demonstration. Coming to the point, I replaced the “ExecuteReader” method with the “ExecuteScalar” method. “ExecuteReader” is generally used to retrieve one or more rows. The “ExecuteScalar” method is optimized to retrieve single values only. It doesn’t mean that you cannot use “ExecuteReader” for retrieving single values. The point is the optimization. The .NET data provider specification prefers to use “ExecuteScalar” if you are trying to retrieve single values from the database.
You can find the other methodologies in the immediate next part of this series. Any comments, suggestions, bugs, errors, feedback etc. are highly appreciated at jag_chat@yahoo.com.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |