Developing Your First ADO.NET Program

In this section you'll plunge into ADO.NET programming and see a C# program that performs the following tasks:

  1. Connects to the SQL Server Northwind database

  2. Retrieves a row from the Customers table

  3. Displays the columns from the row

  4. Closes the database connection

You'll be introduced to many concepts in this section that are fully explored in later chapters. Don't be too concerned about all the details of the concepts at this stage; you'll learn those details in the later chapters.

Listing 1.1 shows the example program, which is contained in the file FirstExample.cs.

Listing 1.1: FIRSTEXAMPLE.CS

start example
 /*   FirstExample.cs illustrates how to:   1. Connect to the SQL Server Northwind database.   2. Retrieve a row from the Customers table using      a SQL SELECT statement.   3. Display the columns from the row.   4. Close the database connection. */ using System; using System.Data.SqlClient; class FirstExample {   public static void Main()   {     try     {       // step 1: create a SqlConnection object to connect to the       // SQL Server Northwind database       SqlConnection mySqlConnection =         new SqlConnection(           "server=localhost;database=Northwind;uid=sa;pwd=sa"         );       // step 2: create a SqlCommand object       SqlCommand mySqlCommand = mySqlConnection.CreateCommand();       // step 3: set the CommandText property of the SqlCommand object to       // a SQL SELECT statement that retrieves a row from the Customers table       mySqlCommand.CommandText =         "SELECT CustomerID, CompanyName, ContactName, Address "+         "FROM Customers "+         "WHERE CustomerID = 'ALFKI'";       // step 4: open the database connection using the       // Open() method of the SqlConnection object       mySqlConnection.Open();       // step 5: create a SqlDataReader object and call the ExecuteReader()       // method of the SqlCommand object to run the SELECT statement       SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();       // step 6: read the row from the SqlDataReader object using       // the Read() method       mySqlDataReader.Read();       // step 7: display the column values       Console.WriteLine("mySqlDataReader[\" CustomerID\"] = "+         mySqlDataReader["CustomerID"]);       Console.WriteLine("mySqlDataReader[\" CompanyName\"] = "+         mySqlDataReader["CompanyName"]);       Console.WriteLine("mySqlDataReader[\" ContactName\"] = "+         mySqlDataReader["ContactName"]);       Console.WriteLine("mySqlDataReader[\" Address\"] = "+         mySqlDataReader["Address"]);       // step 8: close the SqlDataReader object using the Close() method       mySqlDataReader.Close();       // step 9: close the SqlConnection object using the Close() method       mySqlConnection.Close();     }     catch (SqlException e)     {       Console.WriteLine("A SqlException was thrown");       Console.WriteLine("Number = "+ e.Number);       Console.WriteLine("Message = "+ e.Message);       Console.WriteLine("StackTrace:\n" + e.StackTrace);     }   } } 
end example

Note 

You can download all the source files for the programs featured in this book from the Sybex Web site at www.sybex.com. You'll find instructions on downloading these files in the introduction of this book. Once you've downloaded the files, you can follow along with the examples without having to type in the program listings.

Let's go through the lines in FirstExample.cs. The first set of lines is a comment that indicates what the program does:

 /*   FirstExample.cs illustrates how to:   1. Connect to the SQL Server Northwind database.   2. Retrieve a row from the Customers table using      a SQL SELECT statement.   3. Display the columns from the row.   4. Close the database connection. */ 

The next two lines indicate the namespaces being referenced in the program with the using statement:

 using System; using System.Data.SqlClient; 

The System namespace is the root namespace and is referenced so that we can simply use Console .WriteLine() calls in the program, rather than the fully qualified System.Console.WriteLine() call. The System.Data.SqlClient namespace contains the ADO.NET classes for use with SQL Server, including the SqlConnection, SqlCommand, and SqlDataReader classes that are used later in the program. You'll be introduced to these classes shortly, and you'll learn the full details of the ADO.NET classes as you progress through this book.

You handle exceptions that might be thrown in your code by placing the code within a try/catch block. You'll notice that the nine steps are placed within a try/catch block in the Main() method, with the catch block handling a SqlException object that might be thrown by the code in the try block. You'll learn more about this later in the section "Handling Exceptions" after I've discussed the nine steps in the following sections.

Step 1: Create a SqlConnection Object to Connect to the Database

You use an object of the SqlConnection class to connect to a SQL Server database. Step 1 in the Main() method creates a SqlConnection object named mySqlConnection to connect to the SQL Server Northwind database:

 SqlConnection mySqlConnection =   new SqlConnection(      "server=localhost;database=Northwind;uid=sa;pwd=sa"    ); 

The string passed to the SqlConnection constructor is known as the connection string and contains the following elements:

  • server Specifies the name of the computer on which SQL Server is running-localhost in this example; localhost is a common name that refers to the computer on which your program runs. If your database is running on a computer other than the one your program is running on, then you'll need to replace localhost with the name of that computer.

  • database Specifies the name of the database-Northwind in this example.

  • uid Specifies the name of the database user account-sa in this example; sa is a common database user account used by the database administrator (DBA). You can use any database user account as long as it has access to the Northwind database.

  • pwd Specifies the password for the user. The password for the sa user in my database is also sa. You'll need to change pwd to the password for your sa account, or whichever account you specified in uid.

You'll need to change the settings of some or all of the previous elements in your connection string. You might need to speak with your DBA to get the various elements that make up your connection string. Once you have the correct values, you should make the changes to the connection string in your copy of FirstExample.cs.

Note 

A database administrator (DBA) is responsible for performing tasks such as installing the database software, backing up the databases, and so on.

Step 2: Create a SqlCommand Object

Step 2 creates a SqlCommand object named mySqlCommand that is used later to send a SELECT statement to the database for execution.

 SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); 

Step 3: Set the CommandText Property of the SqlCommand Object

You use SQL to work with the information stored in a database. SQL is an industry standard language supported by SQL Server, Access, and Oracle. You use the SQL SELECT statement for retrieving information from a database. You'll learn the basics of SQL in Chapter 3, "Introduction to the Structured Query Language."

Step 3 sets the CommandText property of mySqlCommand created in the previous step to a SELECT statement. This statement will retrieve the CustomerID, CompanyName, ContactName, and Address columns from the row in the Customers table whose CustomerID is ALFKI:

 mySqlCommand.CommandText =   "SELECT CustomerID, CompanyName, ContactName, Address "+   "FROM Customers "+   "WHERE CustomerID = 'ALFKI'"; 

Step 4: Open the SqlConnection Object

Step 4 opens the database connection using the Open() method of the SqlConnection object created in step 1:

 mySqlConnection.Open(); 

Once the connection to the database is open, you can send commands to the database for execution.

Step 5: Run the SELECT Statement

You run the SELECT statement previously set in mySqlCommand by calling the ExecuteReader() method. This method returns a SqlDataReader object that you then use to read the row data returned by the SELECT statement.

Step 5 creates a SqlDataReader object and calls the ExecuteReader() method of mySqlCommand object to run the SELECT statement:

 SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader(); 

Step 6: Read the Row Using the SqlDataReader Object

Step 6 reads the row in mySqlDataReader using the Read() method:

 mySqlDataReader.Read(); 

Step 7: Display the Column Values from the SqlDataReader Object

You can read the value for a column from mySqlDataReader by passing the name of the column in square brackets. For example, mySqlDataReader["CustomerID"] returns the value of the CustomerID column.

Step 7 displays the column values for the CustomerID, CompanyName, ContactName, and Address column values:

 Console.WriteLine("mySqlDataReader[\" CustomerID\"] = "+   mySqlDataReader["CustomerID"]); Console.WriteLine("mySqlDataReader[\" CompanyName\"] = "+   mySqlDataReader["CompanyName"]); Console.WriteLine("mySqlDataReader[\" ContactName\"] = "+   mySqlDataReader["ContactName"]); Console.WriteLine("mySqlDataReader[\" Address\"] = "+   mySqlDataReader["Address"]); 

Step 8: Close the SqlDataReader Object

When you're finished reading rows from a SqlDataReader object, close it using the Close() method. Step 8 calls the Close() method for mySqlDataReader:

 mySqlDataReader.Close(); 

Step 9: Close the SqlConnection Object

When you're finished accessing the database, close your SqlConnection object using the Close() method. Step 9 calls the Close() method for mySqlConnection:

 mySqlConnection.Close(); 

Handling Exceptions

You handle exceptions that might be thrown in your code by placing the code within a try/catch block. You'll notice that the nine steps are placed within a try/catch block, with the catch block handling a SqlException object that might be thrown by the code in the try block. The SqlException class is specifically for use with code that accesses a SQL Server database.

The following example shows how to structure a try/catch block:

 try {   /* code that might throw a SqlException */ } catch (SqlException e) {   Console.WriteLine("A SqlException was thrown");   Console.WriteLine("Number = "+ e.Number);   Console.WriteLine("Message = "+ e.Message);   Console.WriteLine("StackTrace:\n" + e.StackTrace); } 

The properties displayed in the catch block are as follows:

  • Number The error number

  • Message A string containing a description of the error

  • StackTrace A string containing the name of the class and the method from which the exception was thrown

The two most common examples of when a SqlException object is thrown are as follows:

  • Your SqlConnection object is unable to connect to the database. If this happens, you should check the connection string that specifies how to connect to your database.

  • Your SELECT statement contains a mistake in the spelling of a table or column.

The following example output shows what happens when the SqlConnection object in FirstExample.cs is unable to connect to the database because the database is currently down:

 A SqlException was thrown Number = -2 Message = Timeout expired. Possible reasons: the timeout period elapsed prior  to completion of the operation, the server is not responding,  or the maximum pool size was exceeded.  Please see the documentation for further details. StackTrace:    at System.Data.SqlClient.SqlConnection.Open()    at FirstExample.Main() 

You can use the output from your catch block to determine the problem. If the database is down, contact your DBA.

Note 

For brevity, the only program to use a try/catch block in this book is FirstExample.cs. You should use try/catch blocks in your own programs to catch exceptions. For more details on handling exceptions, I recommend the book Mastering Visual C# .NET from Sybex (2002).

In the next section you'll see how to compile FirstExample.cs and run it.

Compiling and Running FirstExample.cs

You can compile the FirstExample.cs program using either the command-line tool that comes with the .NET SDK or VS .NET. In this section, you'll see how to use the command-line version of the compiler for FirstExample.cs program. Later in this chapter, in the section "Introducing Visual Studio .NET," you'll see how to use VS .NET to compile and run a program.

You run the command-line version of the compiler by entering csc in the Command Prompt tool, followed by the name of your program source file. For example, to compile FirstExample.cs, you would enter the following command in the Command Prompt tool:

 csc FirstExample.cs 

If you want to follow along with the examples, start the Command Prompt tool by selecting Start Programs Accessories Command Prompt.

Note 

If you're using Windows XP rather than Windows 2000, start the Command Prompt tool by selecting Start All Programs Accessories Command Prompt.

Next, you need to change directories to where you copied the FirstExample.cs file. To do this, you first enter the partition on your hard disk where you saved the file. For example, let's say you saved the file in the ADO.NET\book\ch01\programs directory of the C partition of your hard disk. To access the C partition, you enter the following line into the Command Prompt tool and then you press the Enter key:

 C: 

Next, to move to the ADO.NET\book\ch01\programs directory, you enter cd followed by ADO.NET\book\ch01\programs:

 cd ADO.NET\book\ch01\programs 

To compile FirstExample.cs using csc, you enter the following command:

 csc FirstExample.cs 

Notice that the name of the program source file follows csc; in this case, it's FirstExample.cs.

If you get an error when running csc, you'll need to add the directory where you installed the SDK to your Path environment variable. The Path environment variable specifies a list of directories that contain executable programs. Whenever you run a program from the command prompt, the directories in the Path variable are searched for the program you want to run. Your current directory is also searched. To set your Path environment variable, do the following:

  1. Select Start Settings Control Panel. Then double-click System and select the Advanced tab.

  2. Click the Environment Variables button and double-click Path from the system variables area at the bottom.

  3. Add the directory where you installed the SDK to your Path environment variable.

  4. Click OK to save your change, and then click OK again on the next dialog.

  5. Restart Command Prompt so that your change is picked up. You should then be able to run csc successfully.

The compiler takes the FirstExample.cs file and compiles it into an executable file named FirstExample.exe. The .exe file contains instructions that a computer can run, and the .exe file extension indicates the file is an executable file.

You run an executable file using the Command Prompt tool by entering the name of that executable file. For example, to run the FirstExample.exe file, you enter the following line in the Command Prompt tool and then you press the Enter key:

 FirstExample 

When you run the program, you should see the following text displayed in your Command Prompt window:

 mySqlDataReader["CustomerID"] = ALFKI mySqlDataReader["CompanyName"] = Alfreds Futterkiste mySqlDataReader["ContactName"] = Maria Anders mySqlDataReader["Address"] = Obere Str. 57 

If you encounter an exception-such as your program can't connect to the database-you should check the connection string set in step 1 of FirstExample.cs, and speak with your DBA if necessary.




Mastering C# Database Programming
Mastering the SAP Business Information Warehouse: Leveraging the Business Intelligence Capabilities of SAP NetWeaver
ISBN: 0764596373
EAN: 2147483647
Year: 2003
Pages: 181

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net