ADO.NET Core
Basics of ADO.NET
Basics of ADO.NET
  • Concepts
    • Database tools overview
      • SSMS & VS Data tools
    • ADO.NET Basics
  • Code
    • Connected mode
      • Create the database
      • Create project
      • Read data
      • Insert data
    • Disconnected mode
      • Create project
      • Read data
      • Insert data
    • GitHub Repo
  • Optional
    • WinForms walkthrough MS
    • Northwind DB
Powered by GitBook
On this page
  • Read data
  • Output
  • Details
  1. Code
  2. Connected mode

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:

PreviousCreate projectNextInsert data

Last updated 2 years ago

LogoADO.NET SqlCommandDot Net Tutorials