Using the SQL Server Data Provider

Một phần của tài liệu Beginning C# 2005 Databases From Novice to Professional phần 2 pot (Trang 45 - 52)

The .NET data provider for SQL Server is in the System.Data.SqlClientnamespace. This data provider communicates directly with the server using its native network protocol instead of through multiple layers.

Table 4-2 describes some important classes in the SqlClientnamespace.

C H A P T E R 4 ■ I N T R O D U C I N G A D O. N E T 71

Figure 4-3.ADO.NET concurrently accessing SQL Server and Access databases

Table 4-2.Commonly Used SqlClientClasses

Class Description

SqlCommand Executes SQL queries, statements, or stored procedures SqlConnection Represents a connection to a SQL Server database SqlDataAdapter Represents a bridge between a dataset and a data source SqlDataReader Provides a forward-only, read-only data stream of the results SqlError Holds information on SQL Server errors and warnings SqlException The exception thrown on a SQL Server error or warning SqlParameter Represents a command parameter

SqlTransaction Represents a SQL Server transaction

Another namespace, System.Data.SqlTypes, maps SQL Server data types to .NET types, both enhancing performance and making developers’ lives a lot easier.

Let’s look at an example that uses the SQL Server data provider. It won’t cover con- nections and data retrieval in detail, but will familiarize you with what you’ll encounter in upcoming chapters.

Try It Out: Creating a Simple Console Application Using the SQL Server Data Provider You’ll build a simple console application that opens a connection and runs a query, using the SqlClientnamespace against the SSE Northwind database. You’ll display the retrieved data in a console window. Follow these steps:

1. Open VCSE and create a new Console Application project named Chapter04. In Solution Explorer, save the solution with Ctrl+S.

2. Right-click the Chapter04project and rename it to SqlServerProvider. 3. Right-click the Program.csfile and rename it to SqlServerProvider.cs. When

prompted to rename all references to Program, you can click either Yes or No.

4. Since you’ll be creating this example from scratch, open SqlServerProvider.cs in Code Editor and replace it with the code in Listing 4-1 (available in the code download, in bcs2005db\code\Chapter04\Listing4_1.txt).

C H A P T E R 4 ■ I N T R O D U C I N G A D O. N E T 72

Listing 4-1.SqlServerProvider.cs using System;

using System.Data;

using System.Data.SqlClient;

namespace Chapter04 {

class SqlServerProvider {

static void Main(string[] args) {

// Set up connection string string connString = @"

server = .\sqlexpress;

integrated security = true;

database = northwind

";

// Set up query string string sql = @"

select

* from

employees

";

// Declare connection and data reader variables SqlConnection conn = null;

SqlDataReader reader = null;

try {

// Open connection

conn = new SqlConnection(connString);

conn.Open();

// Execute the query

SqlCommand cmd = new SqlCommand(sql, conn);

reader = cmd.ExecuteReader();

C H A P T E R 4 ■ I N T R O D U C I N G A D O. N E T 73

// Display output header Console.WriteLine(

"This program demonstrates the use of "

+ "the SQL Server Data Provider."

);

Console.WriteLine(

"Querying database {0} with query {1}\n"

, conn.Database , cmd.CommandText );

Console.WriteLine("First Name\tLast Name\n");

// Process the result set while(reader.Read()) {

Console.WriteLine(

"{0} | {1}"

, reader["FirstName"].ToString().PadLeft(10) , reader[1].ToString().PadLeft(10)

);

} }

catch (Exception e) {

Console.WriteLine("Error: " + e);

} finally {

// Close connection reader.Close();

conn.Close();

} } } }

5. Save the project, and press Ctrl+F5 to run it. The results should appear as in Figure 4-4.

C H A P T E R 4 ■ I N T R O D U C I N G A D O. N E T 74

How It Works

Let’s take a look at how the code works, starting with the usingdirectives:

using System;

using System.Data;

using System.Data.SqlClient;

The reference to System.Datais actually not needed in this small program, since you don’t explicitly use any of its members, but it’s a good habit to always include it.

The reference to System.Data.SqlClientis necessary, since you want to use the simple names of its members.

You specify the connection string with parameters (key-value pairs) suitable for an SSE session:

// Set up connection string string connString = @"

server = .\sqlexpress;

integrated security = true;

database = northwind

";

The connection string contains the parameter integrated security=true;

which specifies Windows Authentication, so any user logged onto Windows can access the SQLEXPRESS instance.

C H A P T E R 4 ■ I N T R O D U C I N G A D O. N E T 75

Figure 4-4.Accessing Northwind via the SQL Server data provider

Note We use Windows Authentication throughout this book. SQL Server Authentication is also avail- able, but it requires users to be defined to the SQLEXPRESS instance. For information on how SQL Server handles user authentication and authorization, see Robin Dewson’s Beginning SQL Server 2005 Express for Developers: From Novice to Professional(Berkeley, CA: Apress, 2007).

You then code the SQL query:

// Set up query string string sql = @"

select

* from

employees

";

Tip We use verbatim strings for both connection strings and SQL, because it allows us to indent the source code conveniently. The connection string is actually parsed before it’s assigned to the connec- tion’s ConnectionStringproperty, so the new lines and extra spaces are inconsequential. SQL can contain extraneous new lines and spaces, so you can format it flexibly to make it more readable and maintainable.

You next declare variables for the connection and data reader, so they’re available to the rest of your code:

// Declare connection and data reader variables SqlConnection conn = null;

SqlDataReader reader = null;

You then create the connection and open it:

try {

// Open connection

conn = new SqlConnection(connString);

conn.Open();

You do this (and the rest of your database work) in a tryblock to handle exceptions, in particular exceptions thrown by ADO.NET in response to database errors, though in this simple example you’re not interested in distinguishing them from other exceptions.

C H A P T E R 4 ■ I N T R O D U C I N G A D O. N E T 76

Here, ADO.NET will throw an exception if the connection string parameters aren’t syntac- tically correct, so you may as well be prepared. If you wait until you enter the tryblock to declare the connection (and data reader) variable, you won’t have it available in the finallyblock to close the connection. Note that creating a connection doesn’t actually connect to the database. You need to call the Openmethod on the connection.

To execute the query, you first create a command object, passing its constructor the SQL to run and the connection on which to run it. Next, you create a data reader by call- ing ExecuteReader()on the command object. This not only executes the query but also sets up the data reader. Note that unlike most objects, you have no way to create a data reader with a newexpression:

// Execute the query

SqlCommand cmd = new SqlCommand(sql, conn);

reader = cmd.ExecuteReader();

You then produce a header for your output, using connection and command proper- ties (Databaseand CommandText, respectively) to get the database name and query text:

// Display output header Console.WriteLine(

"This program demonstrates the use of "

+ "the SQL Server Data Provider."

);

Console.WriteLine(

"Querying database {0} with query {1}\n"

, conn.Database , cmd.CommandText );

Console.WriteLine("First Name\tLast Name\n");

You retrieve all the rows in the result set by calling the data reader’s Readmethod, which returns trueif there are more rows and falseotherwise. Note that the data reader is positioned immediately before the first row prior to the first call to Read:

// Process the result set while(reader.Read()) {

Console.WriteLine(

"{0} | {1}"

, reader["FirstName"].ToString().PadLeft(10) , reader[1].ToString().PadLeft(10)

);

} }

C H A P T E R 4 ■ I N T R O D U C I N G A D O. N E T 77

You access each row’s columns with the data reader’s indexer (here, the

SqlDataReader.Itemproperty), which is overloaded to accept either a column name or a zero-based integer index. You use both to demonstrate the indexer’s use, but using column numbers is more efficient than using column names.

Next, you handle any exceptions, quite simplistically, but at least you’re developing a good habit (we’ll cover exception handling much more thoroughly in Chapter 15):

catch (Exception e) {

Console.WriteLine("Error: " + e);

}

Finally, in a finallyblock, close the data reader and the connection by calling their Closemethods. As a general rule, you should close things in a finallyblock to be sure they get closed no matter what happens within the tryblock:

finally {

// Close connection reader.Close();

conn.Close();

}

Technically, closing the connection also closes the data reader, but closing both (in the previous order) is another good habit. A connection with an open data reader can’t be used for any other purpose until the data reader has been closed.

Một phần của tài liệu Beginning C# 2005 Databases From Novice to Professional phần 2 pot (Trang 45 - 52)

Tải bản đầy đủ (PDF)

(52 trang)