TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

ADO Net Sql Server Connectivity

ADO Net Sql Server Connectivity with introduction, data providers, sql server connectivity, connection, command, datareader, dataset, dataadapter, datatables, web form examples, mvc examples etc.

<< Back to ADO

ADO.NET SQL Server Connection

To connect with SQL Server, we must have it installed in our system. We are using Microsoft SQL Server Management Tool to connect with the SQL Server. We can use this tool to handle database. Now, follow the following steps to connect with SQL Server.

  1. Open Microsoft SQL Server Management Tool
  2. It will prompt for database connection. Provide the server name and authentication.

    ADO Net SQL Server Connection 1

    After successful connection, it displays the following window.

    ADO Net SQL Server Connection 2
  3. Creating Database
  4. Now, create database by selecting database option then right click on it. It pops up an option menu and provides couple of options.

    ADO Net SQL Server Connection 3

    Click on the New Database then it will ask for the database name. Here, we have created a Student database.

    ADO Net SQL Server Connection 4

    Click on the Ok button then it will create a database that we can see in the left window of the below screenshot.

    ADO Net SQL Server Connection 5
  5. Establish connection and create a table
  6. After creating database, now, let's create a table by using the following C# code. In this source code, we are using created student database to connect.

    In visual studio 2017, we created a .NET console application project that contains the following C# code.

    // Program.cs

    using System;
    using System.Data.SqlClient;
    namespace AdoNetConsoleApplication
    {
        class Program
        {
            static void Main(string[] args)
            {
                new Program().CreateTable();
            }
            public void CreateTable()
            {
                SqlConnection con = null;
                try
                {
                    // Creating Connection
                    con = new SqlConnection("data source=.; database=student; integrated security=SSPI");
                    // writing sql query
                    SqlCommand cm = new SqlCommand("create table student(id int not null, 
    				name varchar(100), email varchar(50), join_date date)", con);
                    // Opening Connection
                    con.Open();
                    // Executing the SQL query
                    cm.ExecuteNonQuery();
                    // Displaying a message
                    Console.WriteLine("Table created Successfully");
                }
                catch (Exception e)
                {
                    Console.WriteLine("OOPs, something went wrong."+e);
                }
                // Closing the connection
                finally
                {
                    con.Close();
                }
            }
        }
    }
    

    Execute this code using Ctrl+F5. After executing, it displays a message to the console as below.

    ADO Net SQL Server Connection 6

    We can see the created table in Microsoft SQL Server Management Studio also. It shows the created table as shown below.

    ADO Net SQL Server Connection 7

    See, we have a table here. Initially, this table is empty so we need to insert data into it.

  7. Insert Data into the Table
  8. // Program.cs

    using System;
    using System.Data.SqlClient;
    namespace AdoNetConsoleApplication
    {
        class Program
        {
            static void Main(string[] args)
            {
                new Program().CreateTable();
            }
            public void CreateTable()
            {
                SqlConnection con = null;
                try
                {
                    // Creating Connection
                    con = new SqlConnection("data source=.; database=student; integrated security=SSPI");
                    // writing sql query
                    SqlCommand cm = new SqlCommand("insert into student
    				(id, name, email, join_date)values('101','Ronald Trump','ronald@example.com','1/12/2017')", con);
                    // Opening Connection
                    con.Open();
                    // Executing the SQL query
                    cm.ExecuteNonQuery();
                    // Displaying a message
                    Console.WriteLine("Record Inserted Successfully");
                }
                catch (Exception e)
                {
                    Console.WriteLine("OOPs, something went wrong."+e);
                }
                // Closing the connection
                finally
                {
                    con.Close();
                }
            }
        }
    }
    

    Execute this code by using Ctrl+F5 and it will display the following output.

    ADO Net SQL Server Connection 8
  9. Retrieve Record
  10. Here, we will retrieve the inserted data. Look at the following C# code.

    // Program.cs

    using System;
    using System.Data.SqlClient;
    namespace AdoNetConsoleApplication
    {
        class Program
        {
            static void Main(string[] args)
            {
                new Program().CreateTable();
            }
            public void CreateTable()
            {
                SqlConnection con = null;
                try
                {
                    // Creating Connection
                    con = new SqlConnection("data source=.; database=student; integrated security=SSPI");
                    // writing sql query
                    SqlCommand cm = new SqlCommand("Select * from student", con);
                    // Opening Connection
                    con.Open();
                    // Executing the SQL query
                    SqlDataReader sdr = cm.ExecuteReader();
                    // Iterating Data
                    while (sdr.Read())
                    {
                        Console.WriteLine(sdr["id"] + " " + sdr["name"]+" "+sdr["email"]); // Displaying Record
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("OOPs, something went wrong.\n"+e);
                }
                // Closing the connection
                finally
                {
                    con.Close();
                }
            }
        }
    }
    

    Execute this code by Ctrl+F5 and it will produce the following result. This displays two records, one we inserted manually.

    Output:

    ADO Net SQL Server Connection 9
  11. Deleting Record

This time student table contains two records. The following C# code delete one row from the table.

// Program.cs

using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            new Program().CreateTable();
        }
        public void CreateTable()
        {
            SqlConnection con = null;
            try
            {
                // Creating Connection
                con = new SqlConnection("data source=.; database=student; integrated security=SSPI");
                // writing sql query
                SqlCommand cm = new SqlCommand("delete from student where id = '101'", con);
                // Opening Connection
                con.Open();
                // Executing the SQL query
                cm.ExecuteNonQuery();
                Console.WriteLine("Record Deleted Successfully");
            }
            catch (Exception e)
            {
                Console.WriteLine("OOPs, something went wrong.\n"+e);
            }
            // Closing the connection
            finally
            {
                con.Close();
            }
        }
    }
}

Output:

It displays the following output.

ADO Net SQL Server Connection 10

We can verify it by retrieving data back by using SqlDataReader.


Next TopicADO.NET Connection




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf