By Bill Hamilton
Book Price: $54.99 USD
£34.50 GBP
PDF Price: $43.99
Cover | Table of Contents | Colophon
.NET Framework data provider | Data source access |
|---|---|
SQL Server | Microsoft SQL Server version 7.0 or later |
OLE DB | Data sources using OLE DB |
ODBC | Data sources using ODBC |
Oracle | Oracle client software version 8.1.7 or later |
.NET Framework data provider | Data source access |
|---|---|
SQL Server | Microsoft SQL Server version 7.0 or later |
OLE DB | Data sources using OLE DB |
ODBC | Data sources using ODBC |
Oracle | Oracle client software version 8.1.7 or later |
connectionStrings configuration element to specify a collection of database strings. In prior versions, connection strings were stored in the appSettings element.SqlConnectionStringBuilder to programmatically construct a connection string for SQL Server that connects to the AdventureWorks database using integrated security.BuildConnectionString is shown in .using System;
using System.Data.SqlClient;
namespace BuildConnectionString
{
class Program
{
static void Main(string[] args)
{
// Create a connection string builder
SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder( );
// Define connection string attributes using three techniques
csb.DataSource = "(local)";
csb.Add("Initial Catalog", "AdventureWorks");
csb["Integrated Security"] = true;
// Output the connection string from the connection string builder
Console.WriteLine("Connection string:\n{0}", csb.ConnectionString);
// Create a connection string from the connection string builder
SqlConnection connection = new SqlConnection(csb.ConnectionString);
// Open and close the connection
connection.Open( );
Console.WriteLine("\nConnectionState = {0}", connection.State);
connection.Close( );
Console.WriteLine("ConnectionState = {0}", connection.State);
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}
Add() method, or the indexer. You retrieve and use the connection string using the ConnectionString property.ConnectSqlServer is shown in .using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
namespace ConnectSqlServer
{
class Program
{
static void Main(string[] args)
{
// Connect using .NET data provider for SQL Server and integrated
// security
string sqlConnectString1 = "Data Source=(local);" +
"Integrated security=SSPI;Initial Catalog=AdventureWorks;";
using (SqlConnection connection = new SqlConnection(sqlConnectString1))
{
connection.Open( );
// Return some information about the server.
Console.WriteLine("---.NET data provider for SQL Server " +
"with Windows Authentication mode---");
Console.WriteLine("ConnectionString = {0}\n", sqlConnectString1);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}
// Connect using .NET data provider for SQL Server and SQL Server
// authentication
string sqlConnectString2 = "Data Source=(local);" +
"User Id=sa;Password=password;Initial Catalog=AdventureWorks;";
using (SqlConnection connection = new SqlConnection(sqlConnectString2))
{
connection.Open( );
// Return some information about the server.
Console.WriteLine("\n---.NET data provider for SQL Server " +
"with SQL Server Authentication mode---");
Console.WriteLine("ConnectionString = {0}\n", sqlConnectString2);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}
// Connect using .NET data provider for OLE DB.
string oledbConnectString = "Provider=SQLOLEDB;Data Source=(local);" +
"Initial Catalog=AdventureWorks;User Id=sa;Password=password;";
using (OleDbConnection connection =
new OleDbConnection(oledbConnectString))
{
connection.Open( );
// Return some information about the server.
Console.WriteLine("\n---.NET data provider for OLE DB---");
Console.WriteLine("ConnectionString = {0}\n", oledbConnectString);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}
// Connect using .NET data provider for ODBC.
string odbcConnectString = "Driver={SQL Native Client};" +
"Server=(local);Database=AdventureWorks;uid=sa;pwd=password;";
using (OdbcConnection connection =
new OdbcConnection(odbcConnectString))
{
connection.Open( );
// Return some information about the server.
Console.WriteLine("\n---.NET data provider for ODBC---");
Console.WriteLine("ConnectionString = {0}\n", odbcConnectString);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}SqlConnection object.ConnectSqlServerNamedInstance is shown in .using System;
using System.Data.SqlClient;
namespace ConnectSqlServerNamedInstance
{
class Program
{
static void Main(string[] args)
{
string sqlConnectString = @"Data Source=(local)\SQLExpress;" +
"Integrated security=SSPI;Initial Catalog=master;";
using (SqlConnection connection = new SqlConnection(sqlConnectString))
{
connection.Open( );
// Return some information about the server.
Console.WriteLine("ConnectionString = {0}\n", sqlConnectString);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}
Network Address and Network Library attributes of the connection string.SqlConnection object.ConnectIPAddressSqlServer is shown in .using System;
using System.Data.SqlClient;
namespace ConnectIPAddressSqlServer
{
class Program
{
static void Main(string[] args)
{
string connectString =
"Network Library=dbmssocn;Network Address=127.0.0.1;" +
"Integrated security=SSPI;Initial Catalog=AdventureWorks";
using (SqlConnection connection = new SqlConnection(connectString))
{
connection.Open( );
// Return some information about the server.
Console.WriteLine(
"ConnectionState = {0}\nDataSource = {1}\nServerVersion = {2}",
connection.State, connection.DataSource,
connection.ServerVersion);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}
<system.web> element:<authentication mode="Windows" /> <identity impersonate="true" />
AdventureWorks on the local machine to the configuration file Web.config by updating the <connectionStrings> element within the <configuration> element as follows:<connectionStrings> <add name="AdventureWorks" providerName="System.Data.SqlClient" connectionString="Data Source=(local); Integrated security=SSPI;Initial Catalog=AdventureWorks;"/> </connectionStrings>
IntegratedSecurityFromAspNet is shown in .using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace IntegratedSecurityFromAspNet
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sqlText = "SELECT TOP 10 * FROM Person.Contact";
string connectString =
ConfigurationManager.ConnectionStrings[
"AdventureWorks"].ConnectionString;
DataTable dt = new DataTable( );
SqlDataAdapter da = new SqlDataAdapter(sqlText, connectString);
da.Fill(dt);
foreach (DataRow row in dt.Rows)
Response.Write(row["ContactID"] + " - " + row["LastName"] +
", " + row["FirstName"] + "<br/>");
}
}
}System.Data.OracleClient assembly.ConnectOracle is shown in .using System;
using System.Data.OracleClient;
using System.Data.OleDb;
using System.Data.Odbc;
namespace ConnectOracle
{
class Program Interprocess communication (IPC)
{
static void Main(string[] args)
{
// Connect using .NET data provider for Oracle
string oracleConnectString =
"Data Source=ORCL;User Id=hr;Password=password;";
using (OracleConnection connection =
new OracleConnection(oracleConnectString))
{
connection.Open( );
// Return some information about the server.
Console.WriteLine("---Microsoft .NET Provider for Oracle---");
Console.WriteLine("ConnectionString = {0}\n", oracleConnectString);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}
// Connect using .NET data provider for OLE DB.
string oledbConnectString =
"Provider=MSDAORA;Data Source=ORCL;User Id=hr;Password=password;";
using (OleDbConnection connection =
new OleDbConnection(oledbConnectString))
{
connection.Open( );
// Return some information about the server.
Console.WriteLine("\n---Microsoft .NET Provider for OLE DB---");
Console.WriteLine("ConnectionString = {0}\n", oledbConnectString);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}
// Connect using .NET data provider for ODBC
string odbcConnectString = "Driver={Oracle in OraDb10g_home1};" +
"Server=ORCL;uid=hr;pwd=password;";
using (OdbcConnection connection =
new OdbcConnection(odbcConnectString))
{
connection.Open( );
// Return some information about the server.
Console.WriteLine("\n---Microsoft .NET Provider for ODBC---");
Console.WriteLine("ConnectionString = {0}\n", odbcConnectString);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}OleDbDataReader and uses it to output the FirstName and LastName columns from the first five rows in the Person.Contact table in the AdventureWorks sample database.ConnectOleDbDataSource is shown in .using System;
using System.Data.OleDb;
namespace ConnectOleDbDataSource
{
class Program
{
static void Main(string[] args)
{
string oledbConnectString = "Provider=SQLOLEDB;Data Source=(local);" +
"Initial Catalog=AdventureWorks;Integrated Security=SSPI";
string sqlSelect = "SELECT TOP 5 Title, FirstName, LastName " +
"FROM Person.Contact";
// Create an ODBC Connection
using (OleDbConnection connection =
new OleDbConnection(oledbConnectString))
{
OleDbCommand command = new OleDbCommand(sqlSelect, connection);
// Execute the DataReader
connection.Open( );
OleDbDataReader reader = command.ExecuteReader( );
// Output the data from the DataReader to the console
while (reader.Read( ))
Console.WriteLine("{0} {1}", reader[0], reader[1]);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}
OdbcDataReader and uses it to output the FirstName and LastName columns from the first five rows in the Person.Contact table in the AdventureWorks sample database.ConnectOdbcDataSource is shown in .using System;
using System.Data.Odbc;
namespace ConnectOdbcDataSource
{
class Program
{
static void Main(string[] args)
{
string odbcConnectString = "DRIVER={SQL Server};SERVER=(local);" +
"DATABASE=AdventureWorks;Trusted_Connection=yes;";
string sqlSelect = "SELECT TOP 5 Title, FirstName, LastName " +
"FROM Person.Contact";
// Create an ODBC Connection
using (OdbcConnection connection =
new OdbcConnection(odbcConnectString))
{
OdbcCommand command = new OdbcCommand(sqlSelect, connection);
// Execute the DataReader
connection.Open( );
OdbcDataReader reader = command.ExecuteReader( );
// Output the data from the DataReader to the console
while (reader.Read( ))
Console.WriteLine("{0} {1}", reader[0], reader[1]);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}
OdbcConnection object. The ODBC driver connection string is specified using the ConnectAccessDatabase is shown in .using System;
using System.Data;
using System.Data.OleDb;
namespace ConnectAccessDatabase
{
class Program
{
static void Main(string[] args)
{
string oledbConnectString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
@"C:\Documents and Settings\bill\My Documents\" +
"Northwind 2007.accdb;";
using (OleDbConnection connection =
new OleDbConnection(oledbConnectString))
{
connection.Open( );
// Output some connection and database information.
Console.WriteLine("Connection State: {0}", connection.State);
Console.WriteLine("OLE DB Provider: {0}", connection.Provider);
Console.WriteLine("Server Version: {0}", connection.ServerVersion);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}
Jet OLEDB:Database Password attribute in the connection string to specify the password.OleDbConnection object.ConnectPasswordAccessDatabase is shown in .using System;
using System.Data;
using System.Data.OleDb;
namespace ConnectAccessDatabase
{
class Program
{
static void Main(string[] args)
{
string oledbConnectString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
@"C:\Documents and Settings\bill\My Documents\" +
"Northwind 2007.accdb;" +
"Jet OLEDB:Database Password=password;";
using (OleDbConnection connection =
new OleDbConnection(oledbConnectString))
{
connection.Open( );
// Output some connection and database information.
Console.WriteLine("Connection State: {0}", connection.State);
Console.WriteLine("OLE DB Provider: {0}", connection.Provider);
Console.WriteLine("Server Version: {0}", connection.ServerVersion);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}
Set Database command from the Tools → Security menu is used to set up a database password.ConnectMSAccessDataAspNet.system.web> element:<authentication mode="Windows" /> <identity impersonate="true" />
connectionStrings> element within the <configuration> element:<connectionStrings> <add name="Northwind2007" providerName="System.Data.OleDb" connectionString="Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Documents and Settings\bill\My Documents\ Northwind 2007.accdb;"/> </connectionStrings>
ConnectMSAccessDataAspNet is shown in .using System;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
namespace ConnectMSAccessDataAspNet
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sqlText = "SELECT TOP 10 * FROM Customers";
string connectString =
ConfigurationManager.ConnectionStrings[
"Northwind2007"].ConnectionString;
DataTable dt = new DataTable( );
OleDbDataAdapter da =
new OleDbDataAdapter(sqlText, connectString);
da.Fill(dt);
foreach (DataRow row in dt.Rows)
Response.Write(row["ID"] + " - " + row["Last Name"] +
", " + row["First Name"] + "<br/>");
}
}
}
ConnectExcel is shown in .using System;
using System.Data;
using System.Data.OleDb;
namespace ConnectExcel
{
class Program
{
static void Main(string[] args)
{
// Define connection strings for both default
// Excel .xlsx format and Excel 97-2003 .xls format
string[] oledbConnectString = new string[]
{
"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data Source=..\..\..\Category.xlsx;" +
"Extended Properties=\"Excel 12.0;HDR=YES\";",
"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data Source=..\..\..\Category.xls;" +
"Extended Properties=\"Excel 8.0;HDR=YES\";"
};
foreach (string connectString in oledbConnectString)
{
// Define and open the connection
OleDbConnection connection =
new OleDbConnection(connectString);
connection.Open( );
// Output some connection properties to the console
Console.WriteLine("---CONNECTION---");
Console.WriteLine("Connection.String = {0}\n",
connectString);
Console.WriteLine("Connection.State = {0}",
connection.State);
Console.WriteLine("Connection.Provider = {0}",
connection.Provider);
Console.WriteLine("Connection.ServerVersion = {0}",
connection.ServerVersion);
connection.Close( );
Console.WriteLine( );
}
Console.WriteLine("Press any key to continue.");
Console.ReadKey( );
}
}
}ConnectTextFile is shown in .using System;
using System.Data;
using System.Data.OleDb;
namespace ConnectTextFile
{
class Program
{
static void Main(string[] args)
{
string connectString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data Source=..\..\..\;" +
"Extended Properties=\"text;HDR=yes;FMT=Delimited\";";
OleDb Connection connection = new OleDbConnection(connectString);
connection.Open( );
// Output some connection properties to the console
Console.WriteLine("Connection.String = {0}\n",
connectString);
Console.WriteLine("Connection.State = {0}",
connection.State);
Console.WriteLine("Connection.Provider = {0}",
connection.Provider);
Console.WriteLine("Connection.ServerVersion = {0}",
connection.ServerVersion);
connection.Close( );
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey( );
}
}
}
Extended Properties attribute of the connection. Text files are supported with the text source database type as shown in the following example:"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\..\..\; Extended Properties="text;HDR=yes;FMT=Delimited";
ChangeDatabase() method to change the database for a connection.Connection to the AdventureWorks database using the SQL Server .NET data provider. The database for the connection is then changed to use the ReportServer database. Finally, the connection is explicitly closed.ChangeConnectionDatabase is shown in .using System;
using System.Data.SqlClient;
namespace ChangeConnectionDatabase
{
class Program
{
static void Main(string[] args)
{
string sqlConnectString = "Data Source=(local);" +
"Integrated security=SSPI;Initial Catalog=AdventureWorks;";
using (SqlConnection connection = new SqlConnection(sqlConnectString))
{
Console.WriteLine("ConnectionString = {0}\n",
connection.ConnectionString);
// Open the connection
connection.Open();
Console.WriteLine("=> Connection opened.\n");
Console.WriteLine("Connection.State = {0}", connection.State);
Console.WriteLine("Database = {0}\n", connection.Database);
// Change the database.
connection.ChangeDatabase("ReportServer");
Console.WriteLine("=> Database changed to ReportServer.\n");
Console.WriteLine("Connection.State = {0}", connection.State);
Console.WriteLine("Database = {0}\n", connection.Database);
// Close the connection
connection.Close();
Console.WriteLine("=> Connection closed.\n");
Console.WriteLine("Connection.State = {0}", connection.State);
Console.WriteLine("Database = {0}", connection.Database);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}StateChange event to monitor changes in connection state.SetConnectionPoolingOptions is shown in .using System;
using System.Data;
using System.Data.SqlClient;
namespace SetConnectionPoolingOptions
{
class Program
{
static void Main(string[] args)
{
string sqlConnectString = "Data Source=(local);" +
"Integrated security=SSPI;Initial Catalog=AdventureWorks;";
SqlConnection connection = new SqlConnection( );
// Set up the event handler to detect connection state change
connection.StateChange +=
new StateChangeEventHandler(connection_StateChange);
// Set the connection string with pooling options
connection.ConnectionString = sqlConnectString +
"Connection Timeout=15;Connection Lifetime=0;" +
"Min Pool Size=0;Max Pool Size=100;Pooling=true;";
// Output the connection string and open/close the connection
Console.WriteLine("Connection string = {0}",
connection.ConnectionString);
Console.WriteLine("-> Open connection.");
connection.Open();
Console.WriteLine("-> Close connection.");
connection.Close();
// Set the connection string with new pooling options
connection.ConnectionString = sqlConnectString +
"Connection Timeout=30;Connection Lifetime=0;" +
"Min Pool Size=0;Max Pool Size=200;Pooling=true;";
// Output the connection string and open/close the connection
Console.WriteLine("\nConnection string = {0}",
connection.ConnectionString);
Console.WriteLine("-> Open connection.");
connection.Open();
Console.WriteLine("-> Close connection.");
connection.Close();
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
static void connection_StateChange(object sender, StateChangeEventArgs e)
{
Console.WriteLine("\tConnection.StateChange event occurred.");
Console.WriteLine("\tOriginalState = {0}", e.OriginalState.ToString());
Console.WriteLine("\tCurrentState = {0}", e.CurrentState.ToString());
}
}
}Connection is closed or disposed. The connection pool manager removes expired connections and connections that have had their connection with the server severed from the pool.Connection object should be closed as soon as it is no longer needed so that it is added to or returned to the connection pool. This is done by calling either the Close() or Dispose() method of the Connection. Connections that are not explicitly closed might not be added to or returned to the connection pool.PropertyGrid control.DisplayConnectionPropertyDialog.PropertyGrid control. Accept all default properties including the name propertyGrid1. Add an event handler named onPropertyValueChanged() for the PropertyValueChanged event.Label control below the PropertyGrid control. Set its Text property to Connection String:.TextBox control below the Label control. Name it connectString. Set the ReadOnly property to true. Set the Multiline property to true. Size the control to accommodate about four lines of text.DisplayConnectionPropertyDialog is shown in . You need to add the highlighted code.using System; using System.Windows.Forms; using System.Data.SqlClient; namespace DisplayConnectionPropertyDialog { public partial class Form1 : Form { SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(); public Form1() { InitializeComponent(); propertyGrid1.SelectedObject = scsb; } private void onPropertyValueChanged( object s, PropertyValueChangedEventArgs e) { connectString.Text = scsb.ConnectionString; } } }
DataSource, Initial Catalog, and Integrated Security properties in the property grid. The output is shown in .PropertyGrid control provides a user interface for browsing the properties of an object. Set the SelectedObject property of the PropertyGrid class to the object to display properties for—a SqlConnectionStringBuilder, in this case. The PropertyValueChanged event occurs when a property is changed. In the solution, the event handler displays the updated connection string when a property is changed.
adodb from the .NET tab in Visual Studio .NET's Add Reference Dialog. You'll also need a reference to the Microsoft OLE DB Service Component 1.0 Type Library from the COM tab in Visual Studio .NET's Add Reference Dialog.DisplayDataLinkPropertiesDialog.TextBox control. Name it connectString. Set the MultiLine property = true.Button control. Name it openDialog.Click event handler named openDialog_Click.DisplayDataLinkPropertiesDialog is shown in .using System;
using System.Windows.Forms;
namespace DisplayDataLinkPropertiesDialog
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void openDialog_Click(object sender, EventArgs e)
{
ADODB.Connection adodbConnection = new ADODB.Connection( );
object connection = (object)adodbConnection;
MSDASC.DataLinks dlg = new MSDASC.DataLinks();
dlg.PromptEdit(ref connection);
connectString.Text = adodbConnection.ConnectionString;
}
}
}local), select the Use Windows NT Integrated security radio button, and click the OK button to create the connection string. The completed Data Link Properties dialog is shown in .