0

I'm somewhat new to C# - I have a connection string set in my app web.config called "ApplicationServices" Using C#, how can I write a certain SQL command that retrieves data from my database and set's it to a string that I can operate on?

2 Answers 2

3

Here is the full explanation.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx

//Taken from MSDN
private static void ReadOrderData(string connectionString)
{
    string queryString =
        "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

You can also use an ORM such as LINQ2SQL http://codesamplez.com/database/linq-to-sql-c-sharp-tutorial

EDIT:

How to debug...

Below are some links on how to use the debugging features in visual studio.

http://msdn.microsoft.com/en-us/library/ms165053.aspx http://msdn.microsoft.com/en-us/library/k0k771bt(v=vs.71).aspx http://www.dotnetperls.com/debugging

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

4 Comments

I tried the MSDN method here replacing with my own connection string and SQL query, but I don't see anything being written to the console. What's the best way to go about debugging this?
Are you sure your SQL query is returning records? Try Writing reader.HasRows to the output also try removing the try/finally statements, this will allow the Console to throw any errors. Otherwise look at my edit in my answer there is tutorials on debuging
Looks like I had my table name incorrect in my SQL query - looks like it's working now. Thanks!
+1 for first pointing to ADO.NET and not immediately pushing a newbie toward an ORM, where the learning curve is way steeper!
0

If you are planning on writing a query that returns one single value, you should have a look at ExecuteScalar. See this example for a quick demo on how to retrieve a value from the database and set it to a variable:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

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.