March 2008
Intermediate to advanced
982 pages
22h 43m
English
You need to programmatically construct a connection string.
Use a connection string builder class.
The solution uses SqlConnectionStringBuilder to programmatically construct a connection string for SQL Server that connects to the AdventureWorks database using integrated security.
The C# code in Program.cs in the project BuildConnectionString is shown in Example 1-3.
Example 1-3. Program.cs for BuildConnectionString solution
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( );
}
}
}The output is shown in Figure 1-2.
Figure 1-2. Output for BuildConnectionString solution ...
Read now
Unlock full access