Database Reference
In-Depth Information
Don't worry about the specifics of this message right now. Connections often fail for reasons that
have nothing to do with your code. It may be because a server isn't started, as in this case, or because a
password is wrong or because of some other configuration problem exists. You'll soon look at common
problems in establishing database connections.
How It Works
Let's examine the code in Listing 12-1 to understand the steps in the connection process. First, you
specify the ADO.NET and the SQL Server data provider namespaces so you can use the simple names of
their members.
using System;
using System.Data;
using System.Data.SqlClient;
Then, you create a connection string. A connection string consists of parameters—in other words,
key=value pairs separated by semicolons—that specify connection information. Although some
parameters are valid for all data providers, each data provider has specific parameters it will accept, so
it's important to know what parameters are valid in a connection string for the data provider you're
using; this is explained in detail later in the chapter.
// Connection string
string connString = @"server = .\sql2012; integrated security = true;";
Let's briefly examine each of the connection string parameters in this example. The server
parameter specifies the SQL Server instance to which you want to connect.
server = .\sql2012;
In this statement, . (dot) represents the local server, and the name followed by the \ (slash)
represents the SQL Server instance name running on the database server. So, here you have an instance
of SQL Server 2012 named sql2012 running on the local server.
Tip (local) is an alternative to the . (dot) to specify the local machine, so .\sqlexpress can be replaced with
(local)\sql2012 , or you can write even localhost\sql2012 .
The next clause indicates that you should use Windows Authentication (i.e., any valid logged-on
Windows user can log on to SQL Server).
integrated security = true;
You could alternatively have used sspi instead of true , because they both have the same effect.
Other parameters are available. You'll use one later to specify the database to which you want to
connect.
Next you create a connection (a SqlConnection object), passing it the connection string. This doesn't
create a database session. It simply creates the object you'll use later to open a session.
// Create connection
SqlConnection conn = new SqlConnection(connString);
 
Search WWH ::




Custom Search