Write code to retrieve data from SQL database in C# asp net

Here are the steps to connect SQL database server, access database and retrieve data from a table programmatically in C# asp net.

Steps:

  • Create an object of SqlConnection class
  • Prepare connection string for SqlConnection class object.
  • Create object of SqlCommand class and prepare sql command with types, queries and sql connection object.
  • Open sql connection
  • Execute sql query with cmd.ExecuteReader();
  • Retrieve the data usig SqlDataReader object
  • Close the database connection.

 

Connect to SQL Server database example in C#