Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi, I am currently trying to read in multiple values from the same column in a data base but at diffrent rows.

Below is code

string AlphaX = null, AlphaY = null, BetaX = null, BetaY = null;

               SqlCommand userCommand = userConnection.CreateCommand();

               userCommand.CommandText = "SELECT X, Y FROM [dbo].[Coordinates] WHERE GroupName='Alpha'";

               SqlDataReader reader = userCommand.ExecuteReader();

               while (reader.Read())
               {
                   AlphaX = reader["X"].ToString();
                   AlphaY = reader["Y"].ToString();

                   MessageBox.Show(AlphaX);
                   MessageBox.Show(AlphaY);
               }


I want to be able to store the X and Y values of GroupName 'Beta' next. Do I have to close this connection after having stored the value and do another one or am I missing something?.
Posted

No, you can do a second SqlCommand on the same connection.
 
Share this answer
 
Comments
WurmInfinity 14-Mar-11 8:25am    
Ok. Thx
Hi,

Why you do not execute a general Query like SELECT X, Y, GroupName FROM [dbo].Coordinates], after that, split the query according the GroupName:

C#
while (reader.Read())
{
    string currentGroupName = reader["GroupName"].ToString();
    
    switch (currentGroupName)
    {
        case "Alpha":
            AlphaX = reader["X"].ToString();
            AlphaY = reader["Y"].ToString();
            break;
        case "Beta":
            BetaX = reader["X"].ToString();
            BetaY = reader["Y"].ToString();
            break;
    }
}


In this case you only execute one query and you could close the connection faster than querying the DB twice.

Hope this helps.

Best regards and have a nice day,
Stops
 
Share this answer
 
Comments
WurmInfinity 14-Mar-11 8:33am    
Ok thats wicked. Thanks :D!!!
Christoph Keller 14-Mar-11 8:34am    
You're welcome! Glad to hear that it may help :)
WurmInfinity 14-Mar-11 11:01am    
Ok unfortunatly im not very good with switch statements. The code compiles fine and I understand the logic however, it just wont store the information in the variables for some reason. Any suggestions?
Christoph Keller 14-Mar-11 11:07am    
Is it possible that this is a casing problem?
Try to .ToLower() the currentGroupName and write all cases in lower cases.

Also you could set a breakpoint at the switch-statement to see which groupName you got currently. Perhaps there you see what is going wrong.

Hope this helps.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900