Click here to Skip to main content
15,891,733 members
Please Sign up or sign in to vote.
4.00/5 (3 votes)
See more:
ok so this is probably a really simple question but with all the googleable content on the net im having some trouble narrowing down the answer..

All I want to do is grab a piece of data out of a sql table and assign that piece of data to a variable,

eg.

string aPieceOfData = "A piece of data taken from a sql table"

I can setup a select statement without any problems but how do I use that select statement to grab the data and put it in a variable
Posted

Try:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("SELECT iD, description FROM myTable", con))
        {
        using (SqlDataReader reader = com.ExecuteReader())
            {
            while (reader.Read())
                {
                int id = (int) reader["iD"];
                string desc = (string) reader["description"];
                Console.WriteLine("ID: {0}\n    {1}", iD, desc);
                }
            }
        }
    }


[edit]Typo: Caps lock on while typing... - OriginalGriff[/edit]
 
Share this answer
 
v2
Comments
Pete O'Hanlon 19-Dec-11 15:34pm    
As the OP talks about retrieving a single value to assign to a variable, it would be better to use ExecuteScalar.
Sergey Alexandrovich Kryukov 19-Dec-11 18:39pm    
Agree, but this gives the idea where the data comes from :-)
--SA
OriginalGriff 20-Dec-11 3:47am    
Agreed - but I wanted to show different types of values.
Sergey Alexandrovich Kryukov 19-Dec-11 18:40pm    
...so, my 5.
--SA
AmitGajjar 20-Dec-11 0:21am    
Hi, your answer is correct but want to add more , if you would like to return only single cell information then you can use ExecuteScaler() insetead of ExecuteReader()

thanks
-amit.
C#
string ConnectionString = "Your Data Source";
string Val = "";
using (SqlConnection con = new SqlConnection(ConnectionString ))
{
    con.Open();
    using (SqlCommand com = new SqlCommand("SELECT Empname FROM Emp", con))
    {
         Val = com.ExecuteScalar(); 
    }
}
 
Share this answer
 
Select count(*) as varname from tablename where condiotion=con


use this sql querry. U will get value into varname

using (SqlDataReader reader = com.ExecuteReader())
                        {
                        while (reader.Read())
                            {
                            int count = (int) reader["varname"];
                            Console.WriteLine("ID: {0}\n    {1}", varname);
                            }
                        }
                    }
 
Share this answer
 

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