OdbcDataReader Read() method

Discussion in 'C#' started by fluid, Jul 26, 2006.

  1. #1
    Say i execute the following sql statement:

    SELECT employee_name, employee_age FROM employees WHERE employee_id = 1

    Im using the following code to display the employee name (C#)

    myReader = cmd.ExecuteReader();
    while (myReader.Read())
    {
    string this_name = myReader.GetValue(0).ToString();
    Response.Write(this_name);
    }


    I know for sure just one record is going to be retrieved. How do i display the employee_name without having to loop through the reader?
     
    fluid, Jul 26, 2006 IP
  2. Darrin

    Darrin Peon

    Messages:
    123
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Can you try cmd.ExecuteScalar()?

    it will return one value as an object, and you can convert to a string.
     
    Darrin, Jul 26, 2006 IP
  3. fluid

    fluid Active Member

    Messages:
    679
    Likes Received:
    29
    Best Answers:
    0
    Trophy Points:
    70
    #3
    Sorry my mind wasnt working :eek:

    i just had to change the 'while' to 'if' as follows:

    if(myReader.Read())
    {
    string this_name = myReader.GetValue(0).ToString();
    Response.Write(this_name);
    }
     
    fluid, Jul 26, 2006 IP