Webocreation

Monday, October 11, 2010

Opening and Closing Connections


Opening and Closing Connections

You've now seen all the ingredients you need to create and use a connection. You simply create the Connection object required for your data source, apply the appropriate connection string settings, and open the connection. In an example below, a connection is created to a SQL Server database on the local computer using integrated authentication. The code opens the connection, tests its state, and closes it.
Example. Opening and testing a connection //opining n closing database
// ConnectionTest.cs - Opens and verifies a connection
 
using System;
using System.Data.SqlClient;
 
public class ConnectionTest
{
    public static void Main() 
    {
        SqlConnection con = new SqlConnection("Data Source=localhost;" +
               "Initial Catalog=Northwind;Integrated Security=SSPI");
 
        con.Open();
        Console.WriteLine("Connection is " + con.State.ToString());
    
        con.Close();
        Console.WriteLine("Connection is " + con.State.ToString());
    }
}
The output clearly indicates whether the connection test is successful:
Connection is Open
Connection is Closed

No comments:

Post a Comment