ADO .Net – Display Details of SQL Server Table

Display Details of all Records:

  • We use select query to get the data from the table.
  • We invoke ExecuteReader method to get the data from database table.
  • We use while() loop to display records (as we don’t know how many records are present in database table)
  • Using SQLDataReader object, we can collect the details of each column.
using System;
using System.Data.SqlClient;
namespace Practice
{
            class Program
            {
                        static void Main(string[] args)
                        {
                                    SqlConnection con = null;
                                    try
                                    {
                                                con = new SqlConnection(“data source=.; database=fullstack; integrated security=SSPI”);
                                                con.Open();
                                                Console.WriteLine(“Connected”);
 
                                                String query = “select * from account”;
                                                SqlCommand cm = new SqlCommand(query, con);
                                                SqlDataReader sdr = cm.ExecuteReader();
                                                while (sdr.Read())
                                                {
                                                            Console.WriteLine(sdr[“num”] + ” ” + sdr[“name”] + ” ” + sdr[“balance”]);
                                                }
                                    }
                                    catch (Exception e)
                                    {
                                                Console.WriteLine(“OOPs, something went wrong.” + e);
                                    }
                                    finally
                                    {
                                                con.Close();
                                                Console.WriteLine(“Connection closed”);
                                    }
                        }
            }
}

Scroll to Top