Retrieving a Single Value from the Database

Sometimes, you only need to retrieve a single value from the database, instead of a record or set of records. In this case, though you could use the methods described earlier in this hour to retrieve the value, the Command object provides a better way. Instead of using the DataAdapter object to place the results into a DataSet, you can call the ExecuteScalar() method of the Command object directly. This returns just the single value that you've queried from the database.

The code in Listing 6.5 shows this method of retrieving a single value. There are only three major changes from the example in Listing 6.4. First, the database query uses the Count() SQL function to return a count of all the records ...

Get Sams Teach Yourself ADO.NET in 24 Hours now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.