DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

First Program in ADO.NET

You will learn how to create ADO.NET commands for the console, windows forms, and database connections in this lesson. This programmer serves only as a demonstration of how ADO.NET functions. You will learn everything there is to know about ADO.Net in the ensuing chapters.

First Create Database
Open Visual Studio.

  • Go to Server Explorer. If Server Explorer is not opened go to View Server Explorer.

  • Right click on Data Connections and select Create New SQL Server Database.

  • Fill details like this.

  • Server Name: .\SQLEXPRESS

  • Select Windows Authentication

  • Database Name: Test1

  • Click OK.

Image description

Create Table User in Database

Create table Users
    [Id] [int] IDENTITY(1,1) NOT NULL primary key,
    [Name] [varchar](100) NULL,
    [Address] [varchar](100) NULL,
    [PhoneNo] [varchar](100) NULL

Enter fullscreen mode Exit fullscreen mode

Image description

Add Data in Table
Add some data in table using SQL data table Interface

Image description

Get the Database Connection String
Your tables and database are now ready. Your connection string is in the database's properties.

Right Click on Database Properties
The database you currently have has a table and a connection string. The next step is to establish a database connection and use ADO.Net Commands to fetch the records.

Create the C# Console Application
Create the C# Console application for writing the ADO.NET Code

Image description

Write the Code in Console Application

using System.Data.SqlClient;

string ConString = @"Server=localhost\SQLEXPRESS;Database=Test1;Trusted_Connection=True;";
SqlConnection con = new SqlConnection(ConString);
string SqlQuery = "Select * from Users";
    SqlCommand sqlCommand = new SqlCommand(SqlQuery,con);
    SqlDataReader reader = sqlCommand.ExecuteReader();
    while (reader.Read())
        Console.WriteLine(reader[0].ToString() + "\n" + 
            reader[1].ToString() + "\n" + reader[2].ToString()+"\n"
catch (Exception)
finally { 

Enter fullscreen mode Exit fullscreen mode

Output Of the Code
Now you can see the Records From the Database Using Ado.NET

Image description

Top comments (2)

shawnwildermuth profile image
Shawn Wildermuth

There are some major issues with this code. Primarily, you should be disposing most of the ADO.NET objects (connections, adapters, commands, etc.)

sardarmudassaralikhan profile image
Sardar Mudassar Ali Khan

this is just for the beginners i will post articled on advanced topics in future