Skip to content

Instantly share code, notes, and snippets.

@garyherd
Created October 31, 2013 03:33
Show Gist options
  • Save garyherd/7244028 to your computer and use it in GitHub Desktop.
Save garyherd/7244028 to your computer and use it in GitHub Desktop.
snippet to retrieve data while connected to SQL Server. Uses the SqlDataReader object.
using System.Data.SqlClient;
//Step 1: Handshake with the database
SqlConnection myConnection = new SqlConnection(connection string);
myConnection.Open();
//Step2: Specify the command
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = "T-SQL Here";
myCommand.CommandType = System.Data.CommandType.Text;
//Step2.1 Specify stored procedure
myCommand.CommandText = "NameOfStoredProcedure";
myCommand.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader myDataReader;
myDataReader = myCommand.ExecuteReader();
//Step 3: Use the data
while (myDataReader.Read())
{
//Do something with the data here
}
myConnection.Close(); //don't forget to close the connection !!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment