2

I'm trying to grab information about a particular user from my db:

 public string GetUserData()
    {
        string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(conString))
        {

            SqlCommand com = new SqlCommand("SELECT lastName , phoneNo , creditCardNo , dateOfBirth  FROM UserExtendedDataSet WHERE UserId = @UserId", con);

            com.Parameters.Add("@UserId", SqlDbType.NVarChar).Value = getUserId();

            con.Open();

            string result = Convert.ToString(com.ExecuteScalar());
            StatusLabel.Text = result;
            return result;
        }
    }

The problem is that it returns only the first table data (in this case lastName), i know that I can write separate queries for each field but I assume this would not be really efficient.

Is there anyway to get this data with one query ?

2 Answers 2

3

You need to call ExecuteReader on the command and use the instance of the SqlDataReader returned by the command. ExecuteScalar returns just the first column of the first row.

 using(SqlDataReader reader = com.ExecuteReader())
 {
     if(reader.Read()
     {
       StatusLabel.Text = reader[0].ToString() + " " + reader[1].ToString();
       .... other labels for other fields 
     }
 }

Instead the ExecuteReader moves on the first row (if there is one) after you call the Read method and then every column of the row is available from the reader as an indexed array. (Pay attention to null values before applying any conversion like ToString())

By the way, your tags says MySql but you use Sql Server classes in the namespace SqlClient?

Sign up to request clarification or add additional context in comments.

1 Comment

Yep sorry for mish-mash my tag (autocomplete). Any way thanks very much Steve for help this solve my problem in 100%. +1
0

The reason is because you are only executing the query and ExecuteScalar returns the first row from the database.

string result = Convert.ToString(com.ExecuteScalar());

You may try to use ExecuteReader instead like this:

using(SqlDataReader reader = com.ExecuteReader())
 {
     if(reader.Read())
     {
       //your code here
     }
 }

The MSDN says that ExecuteScalar method:

Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.