Documentation
 
 
 

25.7. Opening a Database Connection

Connections are responsible for handling the physical communication between a data store and a .NET application and is the first object that a developer needs to deal with as all database commands need a database connection before doing anything else.

Because the Connection object is part of a Data Provider, each Data Provider implements its own version. The Connection object for EnterpriseDB .NET Connector is called "EDBConnection".

To access a database you need to create and open a database connection. For the first example we will show how to open a database connection from an ASP.NET page, a Console Application as well as a Windows Form application. The other examples will only be using ASP.NET pages.

25.7.1. Opening a Database Connection using ASP.NET

Example 25-1. Opening a Database Connection via ASP.NET

<% @ Page Language="C#" %>
<% @Import Namespace="EnterpriseDB.EDBClient" %>
<% @Import Namespace="System.Configuration" %>

<script language="C#" runat="server">

private void Page_Load(object sender, System.EventArgs e)
{
	string strConnectionString = ConfigurationSettings.AppSettings
	["DB_CONN_STRING"];
	EDBConnection conn = new EDBConnection(strConnectionString);
	
	try {
 	   conn.Open();
	   Response.Write("Connection opened successfully");
	}
	
	catch(EDBException exp) { exp.ToString(); }
	
	finally {
		conn.Close();
	}
}

</script>

First a connection with the database is established by specifying the server name, port number, user ID, and password. If due to some reason a connection is not to established an error message will be displayed.

Then the user is asked to give the employee id against which the image will be retrieved and saved onto the hard disk. The image is retrieved depending on the 'empID' parameter that is passed in against which the image is retrieved into a byte array. To get the image as a whole we loop through the raw bytes and write out the content via a FileStream into a file called "tips.gif". The following code shows how we would do this:

 
 EDBDataReader reader =  cmd.ExecuteReader(); 
				reader.Read(); 
				if (reader.HasRows) 
				{ Byte[] image = new Byte[Convert.ToInt32
				((reader.GetBytes(0, 0,null, 0, Int32.MaxValue)))]; 
					reader.GetBytes(0, 0, image, 0, image.Length);	 
			FileStream fs = new FileStream(@"c:\tips.gif", FileMode.Create,                   
                      				FileAccess.ReadWrite); 
                          		for(int i=0;i<image.Length;i++) 
						 fs.WriteByte(image[i]);				 
						 	fs.Close();
                                       	 }     
      

 

Once we are done with writing out our content we can close the FileStream object and subsequently the EDBConnection object. If everything goes well you should see the following message:

25.7.2. Opening a Database Connection from a Console Application

Now lets take a look at opening a connection with an EnterpriseDB database using a Console based application.

Before we write the code for the console application, let us create an app.config file for storing the connection string to our database. Whenever you need to make any changes to the connection string, this file is where you need to enter the changed connection string under.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<appSettings>
		<add key="DB_CONN_STRING" value = "Server=127.0.0.1;Port=5444;
		User Id=enterprisedb;Password=enterprisedb;Database=edb"/>
	</appSettings>
</configuration>

Example 25-2. Opening a Database Connection with a Console Based Application

using System;
using System.Data;
using EnterpriseDB.EDBClient;

namespace EnterpriseDB
{
	
	class EDB
	{
		
	  static void Main(string[] args)
	  {
              string strConnectionString = ConfigurationSettings.AppSettings
	      ["DB_CONN_STRING"];
	      EDBConnection conn = new EDBConnection(strConnectionString);
			      
	      try
	      {
		  conn.Open(); 
		  Console.WriteLine("Connection Opened Successfully");
	      }
	      
	      catch(Exception exp)
	      {
		  throw new Exception(exp.ToString());
	      }
	          
	      finally
	      {
		conn.Close();
	      }
	   }
	}
}

Save the file as "EDBConnection-Sample.cs" and compile it with the following command from the folder you saved the "EDBConnection-Sample.cs" file in.

csc /r:EDBDataProvider.dll /out:Console.exe EDBConnection-Sample.cs

After running this command, a Console.exe file should be generated in the same folder which you can execute by typing "Console.exe". You should see something like the following screen:

25.7.3. Opening a Database Connection from a Windows Form Application

Finally, let's cover opening a database connection through a .NET WinForm application.

Save the following code snippet as "WinForm-Example.cs" in a directory of your choice, but it should have both the above mentioned dll's in it.

using System;
using System.Windows.Forms;
using System.Drawing;
using EnterpriseDB.EDBClient;

namespace EDBTestClient
{
	
	class Win_Conn
	{
		static void Main(string[] args)
		{			
			Form frmMain = new Form();
			Button btnConn = new Button();
			btnConn.Location = new System.Drawing.Point(104, 64);
			btnConn.Name = "btnConn";
			btnConn.Text = "Open Connection";
			btnConn.Click += new System.EventHandler(btnConn_Click);

			frmMain.Controls.Add(btnConn);
			frmMain.Text = "EnterpriseDB";
					
			Application.Run(frmMain);
		}

		private static void btnConn_Click(object sender, System.EventArgs e)
		{
			EDBConnection conn = null;
			try
			{
				string connectionString = "Server=10.90.1.29;port=5444;
				username=edb;password=edb;database=edb";
				conn = new EDBConnection(connectionString);
				conn.Open();
				MessageBox.Show("Connection Open");				
			}
			catch(EDBException exp)
			{
				MessageBox.Show(exp.ToString());
			}
			finally
			{
				conn.Close();	
			}
		}
	}
}
 
 

Just change the database connection string to point to the database that you want to connect to then compile the file with the following command:

csc /r:EDBDataProvider.dll /out:WinForm.exe WinForm-Example.cs

After running this command, a WinForm.exe file should be generated within the same folder as you compiled under. You should see something like the following screen:

25.7.4. Opening a Database Connection - Explanation

For both the database connection examples above, we begin by importing the necessary namespace EnterpriseDB.EDBClient for working with an EnterpriseDB database. We first create an instance of EDBConnection called conn. The conn class is then initialized by passing a connection string as a parameter to the constructor for the EDBConnection class. Then finally we call the Open method of the EDBConnection class to open a connection to an EnterpriseDB database.

The connection string contains all the necessary location and authentication information for connecting to an EnterpriseDB server. A valid connection string contains the name/IP address of the server, the name of the database to connect to as well as the EnterpriseDB user login and password

Note: Its compulsory to specify the connection information before opening the connection.

 
 ©2004-2007 EnterpriseDB All Rights Reserved