Team LiB
Previous Section Next Section

Creating Database Connections

As noted earlier, you use the Connection class for the specific data provider to connect to a database. The following examples demonstrate creating SQL, ODBC, and OLE DB connections.

Code Example: Creating a SqlClient Connection
Start example
using System;
using System.Data.SqlClient;

namespace Client.Chapter_13___ADO.NET
{
          class CreatingSQLConnections
          {
                static void Main(string[] args)
                {
                       SqlConnection MyConnection =
                          new SqlConnection("Data Source=(local);"
                          + "Initial Catalog" + "MyDatabase;"
                          + "User ID=sa;Password=");
                       //Creates and opens a connection to the database
                       MyConnection.Open();
                }
          }
}
End example
Code Example: Creating an ODBC Connection
Start example
using System;
using System.Data.Odbc;

namespace Client.Chapter_13___ADO.NET
{
          class CreatingConnectionToODBC
          {
                static void Main(string[] args)
                {
                       OdbcConnection MyConnection = new OdbcConnection(
                        "DRIVER={MySQL};SERVER=TESTSRV;DATABASE="
                        + "MyDatabase;UID=root;PWD=\"\"");
                       MyConnection.Open();
                }
          }
}
End example
Code Example: Creating an OleDb Connection Using an Access Database
Start example

using System;
using System.Data.OleDb;

namespace Client.Chapter_13___ADO.NET
{
          class ConnectingToAccess
          {
                static void Main(string[] args)
                {
                       OleDbConnection MyConnection = new OleDbConnection (
                          @"Provider=Microsoft.Jet.OLEDB.4.0;"
                            + " Data Source = c:\MyAccessDB.mdb");
                       MyConnection.Open();
                }
          }
}
End example
Code Example: Creating an OleDb Connection Using Another OLE DB-Compliant Database (Such As Oracle)
Start example
using System;
using System.Data.OleDb;

namespace MyOleDbClient
{
          class Client
          {
                static void Main(string[] args)
                {
                       OleDbConnection MyConnection = new OleDbConnection (
                       @"Provider=MSDAORA; Data Source ="
                         + " orcl.csharp.com;User ID=Me;" + "Password=pass");
                       MyConnection.Open();
                }
          }
}
End example

Team LiB
Previous Section Next Section