Skip Headers
Oracle® Database Express Edition 2 Day Plus .NET Developer Guide
10g Release 2 (10.2)

Part Number B25312-01
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Master Index
Master Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
View PDF

3 Connecting to the Database

This chapter explains how to connect to the Oracle database. You will be using the application you will build in this chapter as a starting point for work in all subsequent chapters.

This chapter contains the following sections:

Starting a New Project

Follow these steps to start a project in Visual Studio .NET 2003:

  1. Click the New Project button. Alternatively, from the File menu, select New, and then select Project.

    Description of connect01.gif follows
    Description of the illustration connect01.gif

    A New Project dialog box appears.

  2. On the left side of the New Project dialog box under Project Types, select Visual C# Projects.

    On the right side of the New Project dialog box under Templates, select Windows Application.

    For Name, enter HR_Connect_CS.

    For Location, enter C:\HR\Visual Studio Projects.

    Check the Create Directory for Solution box.

    For New Solution Name, enter HRApplication. A solution can contain several projects; when it contains only one project, you can use the same name for both.

    Click OK.

    Description of connect02.gif follows
    Description of the illustration connect02.gif

    If you wish to create project in Visual Basic, select Visual Basic Projects in Project Types instead, and enter HR_Connect_VB under Name.

Adding a Reference

To connect the project to an Oracle database, you must add a reference to the Oracle.DataAccess.dll, which contains the data provider.

  1. If it is not already active, start the Solution Explorer; from the View menu, select Solution Explorer.

    Description of connect03.gif follows
    Description of the illustration connect03.gif

    The Solution Explorer appears in the window.

  2. In the Solution Explorer, select the References node, right click and select Add Reference. Alternatively, select Add Reference from the Project menu.

    Description of connect04.gif follows
    Description of the illustration connect04.gif

    The Add Reference dialog box appears.

  3. Scroll down the list of references (under Component Name), and select Oracle.DataAccess.dll.

    Click the Select button.

    Description of connect05.gif follows
    Description of the illustration connect05.gif

    Click the OK button to add the Oracle Data Provider for .NET to your project.

    Note that the Solution Explorer window now shows Oracle.DataAccess in the References folder.

    Description of connect06.gif follows
    Description of the illustration connect06.gif

    Close the Solution Explorer.

Adding Initial Programmatic Statements

C# using statements and Visual Basic Imports statements allow you to refer to database objects without using lengthy, fully qualified names. By convention, these statements appear at or near the top of a code file, before the namespace or class declaration.

  1. With Form1 active, in View menu select Code, or use the F7 keyboard shortcut.

    Description of connect07.gif follows
    Description of the illustration connect07.gif

  2. Add the statements in Example 3-1 or Example 3-2 to the top of the file.

    Example 3-1 Adding Initial Programmatic Statements: C#

    using Oracle.DataAccess.Client; 
    using Oracle.DataAccess.Types;
    

    Example 3-2 Adding Initial Programmatic Statements: VB

    Imports Oracle.DataAccess.Client 
    Imports Oracle.DataAccess.Types
    
    Description of connect08.gif follows
    Description of the illustration connect08.gif

    Save the changes using the Save icon near the top of the window. Alternatively, from the File menu, select Save, or use the Ctrl+S keyboard shortcut.

Adding Connection Elements

To create a connection interface, you must add the necessary data entry elements to the design form.

  1. With Form1 active, change to design view: from the View menu, select Designer. Alternatively, use the Shift+F7 keyboard shortcut. You may also wish to close the Solution Explorer at this time.

    Description of connect09.gif follows
    Description of the illustration connect09.gif

  2. From the View menu, select Toolbox.

    Description of Connect10.gif follows
    Description of the illustration Connect10.gif

    A Toolbox window appears.

  3. From the Toolbox, under Windows Forms, select a Label and drag it onto Form1.

    Description of connect11.gif follows
    Description of the illustration connect11.gif

    A new label, label1, appears on the form.

  4. Repeat Step 3 twice, adding two more labels to the form (label2 and label3).

    Close the Toolbox.

    Description of connect12.gif follows
    Description of the illustration connect12.gif

  5. Right-click label1, and select Properties.

    Description of connect13.gif follows
    Description of the illustration connect13.gif

  6. Change the Text property from label1 to User ID.

    Description of connect14.gif follows
    Description of the illustration connect14.gif

  7. Repeat Steps 5 and 6 for the other two labels, changing the text to Password and Data Source, respectively.

    Close the Properties window.

    Description of connect15.gif follows
    Description of the illustration connect15.gif

  8. From the View menu, select Toolbox. From the Toolbox, under Windows Forms, select a Text Box and drag it onto Form1.

    Description of connect16.gif follows
    Description of the illustration connect16.gif

    A new text box, textBox1, appears on the form.

  9. Repeat Step 8 twice, adding two more text boxes (textBox2 and textBox3).

    Close the Toolbox.

  10. Right-click textBox1, and select Properties.

    Description of connect17.gif follows
    Description of the illustration connect17.gif

  11. In Properties, under Appearance, remove the text in the Text property.

    Description of connect18.gif follows
    Description of the illustration connect18.gif

  12. In Properties, under Design, change the value of (Name) to userID.

    Description of connect19.gif follows
    Description of the illustration connect19.gif

  13. Repeat Steps 10 through 12 twice, changing textBox2 into password and textBox2 into dataSource.

    For the password text box, under Behavior category, change the value of PasswordChar property to *. This will hide the password when it is entered.

    Description of connect20.gif follows
    Description of the illustration connect20.gif

  14. Close the Properties window.

  15. From the View menu, select Toolbox. In the Toolbox, under Window Forms, select Button and drag it onto Form1.

    Description of connect21.gif follows
    Description of the illustration connect21.gif

  16. Right-click button1, and select Properties. The Properties window appears.

  17. In the Properties window, change the Text property to Connect.

    Description of connect22.gif follows
    Description of the illustration connect22.gif

  18. Under Design, change the (Name) property to connect.

    Description of connect23.gif follows
    Description of the illustration connect23.gif

  19. Save the changes using the Ctrl+S keyboard shortcut.

  20. Click the lightning icon (Events) at the top of the Properties window.

    Description of connect24.gif follows
    Description of the illustration connect24.gif

  21. Ensure that the Click event is called connect_Click. Save changes.

    Description of connect25.gif follows
    Description of the illustration connect25.gif

Using the Connection Object

The OracleConnection object specifies the Oracle Database used by the application.

  1. The Easy Connect naming method enables application clients to connect to a database without using any configuration files, simply by specifying the data source attribute through syntax shown in Example 3-3:

    Example 3-3 Easy Connect Naming Method Syntax for Data Source

    user id=id;password=psswd;data source=host:port/service_name
    
    

    Where:

    • id is the user id; we will use hr to access the HR schema.

    • psswd is the password; in this book, we use hr password for the HR schema.

    • host is the DNS name of the server machine to which the XE client will make the connection, such as hr-server in the following example of valid connections.

    • port [optional], if not specified, uses the default value of 1521, which is the server port number from which the client connects to the database.

    • service_name [optional], if not specified, the EZ Connect Adapter for XE client will connect to the default service on the host, preconfigured as XE in the listener.ora file on the XE server.

      Note that the default service is a new feature for Oracle Database XE. If you used other Oracle client software, such as Instant Client for Oracle Database Enterprise Edition, you must supply the service name.

    Some valid connection strings include:

    user id=hr;password=hr;data source=hr-server
    user id=hr;password=hr;data source=hr-server:1521
    user id=hr;password=hr;data source=hr-server:1521/XE
    
    
  2. Example 3-4 and Example 3-5 show how to instantiate a database connection string.

    Example 3-4 Creating an OracleConnection Object: C#

    Add this class variable after the GUI elements you created in the previous section.

    private OracleConnection conn = new OracleConnection();
    

    Example 3-5 Creating an OracleConnection Object: VB

    Add this class variable after the line that starts as Inherits, near the top of the file, in the Form1 class declaration.

    Dim conn As New OracleConnection
    
    
    Description of connect26.gif follows
    Description of the illustration connect26.gif

  3. Before a connection can be open, it must be built from user input for the User ID, Password, and Data Source. Add the code in Example 3-6 or Example 3-7 to your application. Note that the Open() method makes the actual connection. Add this code into the connect_Click() method (for C#) or subroutine (VB).

    Example 3-6 Building and Opening a Connection: C#

    conn.ConnectionString = "User Id=" + userId.Text + ";Password=" + password.Text +
      ";Data Source=" + dataSource.Text + ";";
    conn.Open();
    

    Example 3-7 Building and Opening a Connection: VB

    conn.ConnectionString = "User Id=" + userId.Text + ";Password=" + & _
      password.Text + ";Data Source=" + dataSource.Text + ";"
    conn.Open()
    
    
    Description of connect27.gif follows
    Description of the illustration connect27.gif

  4. As part of good programming practice, add the code in Example 3-8 and Example 3-9 after the Open() call of Form1. This will disable the Connect button after a connection is successfully made.

    Example 3-8 Disabling the Connect Button: C#

    connect.Enabled = false;
    

    Example 3-9 Disabling the Connect Button: VB

    connect.Enabled = false
    
    
  5. Save the application.

Running the Application

The following steps show how to run the application created in the previous sections.

  1. With Form1 active, from the Debug menu, select Start. Alternatively, use the F5 keyboard shortcut.

    Description of connect28.gif follows
    Description of the illustration connect28.gif

    After the application is built successfully, the Form1 window appears.

  2. Enter the user ID, the password, and the data source information, and click Connect. If you are using a local database, located on the same machine as the .NET client, you may leave the data source field blank.

    Description of connect29.gif follows
    Description of the illustration connect29.gif

  3. Note that after a successful connection, the Connect button is disabled.

    Description of connect30.gif follows
    Description of the illustration connect30.gif

Error Handling

Oracle Data Provider for .NET contains three classes for error handling and support:

  1. The .NET languages use Try-Catch-Finally structured error handling. Change the code in Form1, as indicated in Example 3-10 and Example 3-11, which are simple implementations of the Try-Catch-Finally syntax.

    Example 3-10 Error Handling with Try-Catch-Finally Syntax: C#

    try
    {
      conn.Open();
      connect.Enabled = false;
    }
    
    catch (Exception ex)
    {
      MessageBox.Show(ex.Message.ToString());
    }
    
    finally
    {
       conn.Dispose();
    }
    

    Example 3-11 Error Handling with Try-Catch-Finally Syntax: VB

    Try
      conn.Open()
      connect.Enabled = false
    
    Catch ex As Exception
      MessageBox.Show(ex.Message.ToString())
    
    Finally
      conn.Dispose()
    End Try
    
    
  2. Before testing this code, stop the database. From the Start button, select All Programs, then select Oracle Database 10g Express Edition, and select Stop Database.

    Description of error01.gif follows
    Description of the illustration error01.gif

  3. The database will begin to shut down. You should see a Stop Database window. Do not proceed with the following steps until it indicates that the "OracleServiceXE service was stopped successfully".

    Description of error02.gif follows
    Description of the illustration error02.gif

  4. Run the application again, as described in section "Running the Application", and attempt to connect. The error caught when the database is unavailable appears as "ORA-12560: TNS:protocol adapter error".

    Description of error03.gif follows
    Description of the illustration error03.gif

    While this approach will capture errors encountered when connecting to the database, the message is not very informative for the end user.

  5. Add another catch statement to trap common database errors and to display these errors in a more user-friendly manner. Insert Example 3-12 or Example 3-13 code before the generic catch statement.

    Example 3-12 Catching Common Database Error Messages: C#

    catch (OracleException ex)
    {
      switch (ex.Number)
      {
        case 1:
          MessageBox.Show("Error attempting to insert duplicate data.");
          break;
        case 12560:
          MessageBox.Show("The database is unavailable.");
          break;
        default:
          MessageBox.Show("Database error: " + ex.Message.ToString());
        break;
      }
    }
    

    Example 3-13 Catching Common Database Error Messages: VB

    Catch ex As OracleException ' catches only Oracle errors
      Select Case ex.Number
        Case 1
          MessageBox.Show("Error attempting to insert duplicate data.")
        Case 12560
          MessageBox.Show("The database is unavailable.")
        Case Else
          MessageBox.Show("Database error: " + ex.Message.ToString())
      End Select
    
    

    The Case statements should be ordered from most specific to most general. If there are no OracleExceptions, the first Catch statement branch (Example 3-12 or Example 3-13) is skipped. The second Catch statement (in Example 3-10 or Example 3-11) catches all other Exceptions.

  6. Run the application again, as described in section "Running the Application". After implementing Example 3-12 or Example 3-13, the ORA-12560 error appears as "The database is unavailable.":

    Description of error04.gif follows
    Description of the illustration error04.gif

  7. The Finally code block is always executed. If the connection object's Dispose() method call is in the Finally code block, the database connection will always be closed after the Try-Catch-Finally block is complete. Attempting to close a closed database connection does not cause an error. If the database is unavailable, the database connection is not opened, so the Finally code block attempts to close a connection that does not exist, making these calls irrelevant. However, placing Dispose() in the Finally code block guarantees that the connection is closed.

  8. Before proceeding, restart the database. From the Start button, select All Programs, then select Oracle Database 10g Express Edition, and select Start Database.

    Description of error05.gif follows
    Description of the illustration error05.gif

  9. The database services will begin to start. You should see a Start Database window. Do not proceed with the following steps until it indicates that the "OracleServiceXE service was started successfully".

    Description of error06.gif follows
    Description of the illustration error06.gif

Closing the Database Connection

  1. A connection Dispose() method closes and disposes the connection, as shown in Example 3-14 and Example 3-15.

    Example 3-14 Closing and Disposing a Connection: C#

    conn.Dispose();
    

    Example 3-15 Closing and Disposing a Connection: VB

    conn.Dispose()
    
    
  2. C# has an alternative syntax that disposes of a connection when it goes out of scope, through the using keyword, as shown in Example 3-16.

    Example 3-16 Closing and Disposing a Connection when Out of Scope: C#

    using (OracleConnection conn = new OracleConnection())
    {
      conn.Open();
      // application code
      ...
    }