newbie retrieving a single value from the DB

  • Thread starter Thread starter Carlos
  • Start date Start date
C

Carlos

Hi all,

I am new using ADO .Net, and my impression is that
the client always tries to retrieve a collection of data
to process. There is the case in which a single value is expected to be
retrieved, and I do not know how to do it using ADO .Net. Can somebody
provide a code snippet with such case (using the sqlclient namespace)

Thanks,

Carlos.
 
If you just want a single value to be retrieved using a SELECT statement,
use the ExecuteScalar method. Example below:
SqlConnection sqlconnection1 = new
SqlConnection("Server=SERVERNAME;Integrated Security=true;");
sqlconnection1.Open();
SqlCommand sqlcommand1 = sqlconnection1.CreateCommand();
sqlcommand1.CommandText = "SELECT 'TEST'";
Object ob = sqlcommand1.ExecuteScalar(); // returns "TEST"

HTH,
Sushil.
 
Back
Top