Console Application To Display Data From SQL Server

Console Application To Display Data From SQL Server

In this post we will learn How to Create a Console Application To Display Data From SQL Server. A console application is a computer program designed to be used via a text-only computer interface, such as a text terminal, the command line interface of some operating systems (Unix, DOS, etc.).

Steps To Create Console Application:

1. Open Visual Studio > Click New Project > Choose Console Application.

2. This will open c# code page, Code for our app is as follows:

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=dev;User ID=sa;Password=sa");
            con.Open();

            SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM users", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            foreach (DataTable dt in ds.Tables)
            {
                Console.WriteLine("User Details Are Following:");
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    Console.Write(dt.Columns[curCol].ColumnName.Trim() + "\t");
                }
                for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                {
                    for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                    {
                        Console.Write(dt.Rows[curRow][curCol].ToString().Trim() + "\t");
                    }
                    Console.WriteLine();   
                }
            }
        }
    }
}