News
  • Favorite
  • Facebook
  • Twitter
  • LinkedIn

Microsoft Press Pearson Education (InformIT)
Skip Navigation Links
Pearson Education (InformIT)
How to: Test that an Application can establish a Connection to Oracle Database using C#

Sometimes your application connects to database for querying, inserting and deleting data from tables. You need to make sure that the database is running and accept incoming queries across the network. For Oracle Databases you can use tnsping command to test that the database is running as follows:

tnsping [Net Service Name] [Count]

But if you want to make sure that your application can establish a connection to Oracle Database?

Using the Code:

To make sure that your application can establish a connection to database, follow these steps:

1.       Create a new windows application using Visual Studio 2005/2008/2010.

2.       Rename Form1 to ConnectionForm.

3.       Add a TextBox to the ConnectionForm and rename it to DataSourceTextBox.

4.       Add another TextBox to the ConnectionForm and rename it to UserIdTextBox.

5.       Add another TextBox to the ConnectionForm and rename it to PasswordTextBox and set the PasswordChar property to * character.

6.       Import the System.Data and System.Data.OracleClient namespaces using the following statement:

using System.Data;

using System.Data.OracleClient;

7.       The System.Data namespace provides access to classes that represent the ADO.NET architecture. ADO.NET lets you build components that efficiently manage data from multiple data sources.

8.       The System.Data.OracleClient namespace is the .NET Framework Data Provider for Oracle.

9.       Add an ErrorProvider component to the ConnectionForm and name it errorProvider. The Error Provider  provides a user interface for indication that a control on the form has an error associated with it.

10.    Add a Button to the ConnectionForm and name it TestConnButton and double click the TestConnButton in the designer to create the Click event handler in the code.

11.   Add the following code to the TestConnButton Click Event Handler:

private void TestConnButton_Click(object sender, EventArgs e)

{

    try

    {

        errorProvider.Clear();

 

        if (string.IsNullOrEmpty(DataSourceTextBox.Text))

        {

            errorProvider.SetError(DataSourceTextBox, "Required");

            return;

        }

 

        if (string.IsNullOrEmpty(UserIDTextBox.Text))

        {

            errorProvider.SetError(UserIDTextBox, "Required");

            return;

        }

 

        if (string.IsNullOrEmpty(PasswordTextBox.Text))

        {

            errorProvider.SetError(PasswordTextBox, "Required");

            return;

        }

 

        connString = "Data Source={0};Persist Security Info=True;"

            + "User ID={1};Password={2};Unicode=True";

        connString = string.Format(connString, DataSourceTextBox.Text,

            UserIDTextBox.Text, PasswordTextBox.Text);

        OracleConnection oracleConnection = new OracleConnection(connString);

        oracleConnection.Open();

 

        MessageBox.Show("Test Connection Succeeded", "Success",

            MessageBoxButtons.OK, MessageBoxIcon.Information);

 

        oracleConnection.Close();

    }

    catch (OracleException ex)

    {

        MessageBox.Show(ex.Message, ex.Message,

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    catch (InvalidOperationException ex)

    {

        MessageBox.Show(ex.Message, ex.Message,

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message, ex.Message,

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    finally

    {

    }

}

a.       First of all we clear any error in the errorProvider component by calling the Clear method of the errorProvider.

b.      We then check that the user enters a value in the DataSourceTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

c.       We then check that the user enters a value in the UserIdTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

d.      We then check that the user enters a value in the PasswordTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

e.      We create a string variable that holds the connection string that contains placeholders for data source, user Id and password.

f.        Replace the place holders of the connString instance using string.Format method.

g.       Create an instance of the OracleConnection class, name it oracleConnection and pass the connection string to the constructor of the OracleConnection class.

h.      We then call oracleConnection open method to establish a connection to the database. This stage determines if the connection is established or not.

i.         If the connection is established a message box will be displayed stating that “Test Connection Succeeded “.

j.        If the connection could not be established a message box will be displayed stating that there is an exception and the exception message is displayed. You can use the exception message to review the error and test again.

k.       We then call oracleConnection close method to close the database connection and releases any resources associated with the connection. The Close method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled.

 

12.   Now compile and run the application.

13.   Enter any TNS Service Name in the DataSourceTextBox, user name in the UserIdTextBox and password in the PasswordTextBox and click on the TestConnButton.

14.   You will be notified if the connection to the database is established or not.

Now you have an application that can make sure that your application can test establishing a connection to Oracle Database or not.

(28) Comments

Blog Message jordan 13 Black infrared 23

Their large network of lawyers allows them to serve the Ocala area as well as the entire state of Florida. Israel surrounded a number of houses in the center of the refugee camp, including the house of Sheikh Bassam Ragheb al Sa'di, wanted by Israel for alleged activities in Islamic Jihad. jordan 13 Black infrared 23 http://lassa.srfo.org/UserFiles/jordan13Blackinfrared23/


Blog Message nike tn vrai

On est bien d鈥檃ccord que la France a perdu ce match 0-1 mardi soir au Stade de France. nike tn vrai http://www.atlanticabretagne.com/asp/chaussure-tn-44.asp


Blog Message burberry shop nederland

http://www.borlettoweb.com/2014blog/burberrys/www-burberry-outlet-online.html www burberry outlet online burberry shop nederland http://www.borlettoweb.com/2014blog/burberrys/burberry-shop-nederland.html


Blog Message sac celine boutique en ligne

3Ces questionnements nous conduisent à mener une rétrospective sur la place des zones humides dans les politiques d'aménagement des espaces naturels du Nord Pas de Calais (2) et nous permettent de pointer les disparités dans le processus d'intégration des zones humides de la région (3). sac celine boutique en ligne http://www.getridofmypests.net/?page=sac-celine-boutique-en-ligne


Blog Message ceinture hermes pas chere

Cela peut 锚tre une mani猫re 茅vidente d茅sesp茅r茅e pour sauver de l'argent, mais beaucoup d'Am茅ricains n'ont tout simplement pas le faire. Rechercher tous les coins de votre maison pour les pi猫ces de monnaie. Votre salle de lavage, table de chevet ou une commode, et les voitures sont d'excellents endroits pour trouver de bonnes quantit茅s de changement. Maintenant, une fois tous ces changements sont recueillis, ne vont pas le prendre pour une machine de Coinstar ou un dispositif qui vous donne l'argent pour votre pi猫ce. Ces machines prennent autour de 0,10 $ pour chaque dollar, qui ajoute tr猫s rapidement. Rouler vos pi猫ces de monnaie et de les prendre 脿 la banque. La banque d茅poser ces pi猫ces directement dans votre compte d'茅pargne. Revenu mensuel estimatif: $ 10 ceinture hermes pas chere http://www.zstrebovska-ustino.cz/?id=ceinture-hermes-pas-chere


Blog Message prix sac celine neuf

Evacuation de camps de roms: "ill茅gale, inefficace et co没teuse", selon le Haut Comit茅 prix sac celine neuf http://www.khastuban.com/?id=prix-sac-celine-neuf


Blog Message nike magista prix

Les Nike Zoom Supreme Court Low ressemblent 脿 des skate shoes et poss猫dent une semelle interne Zoom Air. nike magista prix http://www.ampere.cnrs.fr/images/foot.php


Blog Message celine luggage pas cher

Les 4 cours peuvent suivis sur plusieurs ann (exemple de formule: 2 cours en 2013 14 + 2 cours en 2014 15, etc.). celine luggage pas cher http://alltoptoday.com/?top=celine-luggage-pas-cher


Blog Message wholesale burberry cologne

http://www.borlettoweb.com/2014blog/burberrys/burberry-outlet-usa-hostels.html burberry outlet usa hostels wholesale burberry cologne http://www.borlettoweb.com/2014blog/burberrys/wholesale-burberry-cologne.html


Blog Message ray ban sunglasses

Hello! I simply would like to give an enormous thumbs up for the nice information you might have right here on this post. I will probably be coming again to your weblog for extra soon. ray ban sunglasses http://www.rayban-glasses.net


Blog Message huf burberry fitted

http://www.borlettoweb.com/2014blog/burberrys/burberry-outlet-orlando.html burberry outlet orlando huf burberry fitted http://www.borlettoweb.com/2014blog/burberrys/huf-burberry-fitted.html


Blog Message burberry factory outlet rome

http://www.borlettoweb.com/2014blog/burberrys/burberry-europe-outlet-hit-bg.html burberry europe outlet hit bg burberry factory outlet rome http://www.borlettoweb.com/2014blog/burberrys/burberry-factory-outlet-rome.html


Blog Message cheap snapbacks

a hats. With the development of fitted caps, our store is getting better and better, has sold out about 2000 caps in a week. its a good news for us. So if you take a time cheap wholesale snapbacks sale,cheap 59fifty hats sale,create custom 59fifty hats sale,59fifty baseball hats sale,wholesale 59fifty hats sale,custom 59fifty hats sale,blank 59fifty hats sale,customize your own 59fifty hats sale,59fifty hats wiki sale,beanies sale, beanie sale, snowboard beanies sale, headwear sale, beanie caps sale, neff beanies sale, to listen and chat with us, you'll find that wewould offer you another surprise. We will be your friends to talk and hear. cheap snapbacks hats,wholesale snapbacks hats,wholesale 59fifty hats,beanies hats wholesale,new era snapbacks hats,new era beanies hatsLots of retro snapback new era hats for sale on our store are popular with the consumers all over the world. 59fifty Caps will be quarterly updated, and then you will get more eye-popping splendors of new caps or new era hats. If you can tell us what you like, or any styles you want. We will try our best to help you on the excellent quality and competitive price of flex fit baseball caps. Thus, as consumers in the purchase of caps, do not just look at the price,one cap depends on the quality and materials, also compliance with national standards. You will get the best for you. At the new-snapback-new era hats, the choice of what you want will be the most difficult decision to make. Just join us to get some fashionable caps, try it. Also they are adjustable sizing to make you feel comfortable, no needed to loose or tighten to make your caps comfortable. They are almost your size. For a range cheap snapbacks http://www.inscorea.com/info/cheap-snapbacks-3_3467.html


Blog Message michael kors wallet black friday 2014

My Coke Rewards Holiday Gift Card Stock Up Instant Win Sweepstakes where US residents can win gift cards worth up to $5,000. The Holiday Gift Card Stock Up Instant Win Sweepstakes ends on 1/30/10. michael kors wallet black friday 2014 http://andoduong.com/?pid=michael-kors-wallet-black-friday-2014


Blog Message discount burberry wallet

http://www.borlettoweb.com/2014blog/burberrys/burberry-outlet-online-941-filing.html burberry outlet online 941 filing discount burberry wallet http://www.borlettoweb.com/2014blog/burberrys/discount-burberry-wallet.html

First Previous 1 2 Next Last 
Rating
Name
Email
Comment