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
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
4 Comments
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 debugingIf 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