Read data

Read data

The program class should have the code as shown below to read the data from the database which we just created:

using System;
using System.Data.SqlClient;

namespace ConnectedDemo;

class Program
{
    static string server = "(localdb)";
    static string instance = "mssqllocaldb";
    static string database = "StudentDB";
    static string authentication = "Integrated Security = true";
    static string ConString = $"Data Source={server}\\{instance}; Initial Catalog={database};{authentication}";
    
    static void Main(string[] args)
    {
        ReadData();
        Console.ReadKey();
    }

    static void ReadData()
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(ConString))
            {
                // Creating SqlCommand objcet   
                var cm = new SqlCommand("select * from student", connection);
        
                // Opening Connection  
                connection.Open();
        
                // Executing the SQL query  
                var sdr = cm.ExecuteReader();
                while (sdr.Read())
                    Console.WriteLine(sdr["Name"] + ",  " + sdr["Email"] + ",  " + sdr["Mobile"]);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("OOPs, something went wrong.\n" + e);
        }
    }
}

Output

Verify that the output from the program looks as below:

Anurag,  Anurag@dotnettutorial.net,  1234567890
Priyanka,  Priyanka@dotnettutorial.net,  2233445566
Preety,  Preety@dotnettutorial.net,  6655443322
Sambit,  Sambit@dotnettutorial.net,  9876543210

Details

For a detailed explanation, read the following link:

Last updated