ADO.NET Tutorial (1/1)

Introduction

ADO.NET is a set of classes that expose data access services to the .NET programmer [1]. In this tutorial we will show how to use ADO.NET to work with Microsoft SQL Server.

Prerequisites

In this tutorial we will use LocalDB. If you are not familiar with LocalDB, our LocalDB tutorial will explain all you need to know to proceed with the examples in this tutorial.

Connecting to a LocalDB instance

For our first example we assume that we want to connect to the default LocalDB instance. Our example assumes LocalDB 2012 is used so the connection string for the default instance is "Data Source=(LocalDb)\\v11.0;Integrated Security=True".

The System.Data.SqlClient.SqlConnection [2] class is used to connect to a SQL server.

The example below is a C# console application that shows the use of the SqlConnection class to connect to the default LocalDB instance. After the SqlConnection instance is created, the Open() function is used to open the connection.

File: Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LocalDbConnection1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string connectionString = "Data Source=(LocalDb)\\v11.0;Integrated Security=True";
                using (System.Data.SqlClient.SqlConnection connection =
                    new System.Data.SqlClient.SqlConnection(connectionString))
                {
                    Console.WriteLine("Connection state: {0}", connection.State);
                    connection.Open();
                    Console.WriteLine("Connection state: {0}", connection.State);

                    Console.WriteLine("List of databases:");
                    using (System.Data.SqlClient.SqlCommand command =
                        new System.Data.SqlClient.SqlCommand("SELECT * FROM master.dbo.sysdatabases", connection))
                    using (System.Data.SqlClient.SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine("\t{0}", reader[0]);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception thrown");
                Console.WriteLine(e);
            }
        }
    }
}

The example uses the SqlCommand class to show a list of databases. We will discuss sending SQL commands later.

The output should be similar to this:

Program Output
Connection state: Closed
Connection state: Open
List of databases:
        master
        tempdb
        model
        msdb
Press any key to continue . . .

References

  1. MSDN: ADO.NET
  2. MSDN: SqlConnection Class

blog comments powered by Disqus

Copyright(c) 2006-2015 Xavier Leclercq | Privacy policy

Home
Contact Us
Search