Got first assignment about database connection from your lecturer??? you’ve come to the right place mate ! I know U’ve been looking for this code , so enjoy it , it’s “trial & error” time !
First, let me tell you about the types of ADO .NET programming, there are two types of it. There are DataSet and OleDbCommand.
The difference is, on DataSet, instances of this class represent in-memory caches of data, so you don’t have to maintain an active connection to modify the contents of a datasource. It is a better way than using OleDbCommand, which in this approach, SQL statements are executed directly on the datasource, very wasteful right?
But, this article are just for dummies =P , so I’m using OleDbCommand on it (for Oracle, it’s named OracleCommand ). OK then, first, you must add a reference to your project. View the solution explorer then right-click at your project’s root, choose add reference. On .NET tab, choose the System.Data.OracleClient. Now, your Oracle-Client is ready for use!
For opening an Oracle connection, you need at least this three namespaces ;
using System;
using System.Data;
using System.Data.OracleClient;
remember that an Oracle-Client must have already installed on your PC. In this example, I used Oracle XE as my Oracle-Client service. All Oracle-Client have the same methods to get connected, you just have to change the SID, pretty simple mate !
Now, it’s time for the best part, the Oracle connection string. Please behave nicely =P
private OracleConnection conn;
public bool OpenConnection(string SID, string user, string password)
{
try
{
//instance new oracle connection
conn = new OracleConnection(“Data Source=”+SID+ “; User Id=”+user+”; Password=”+password+”;”);
//open the connection
conn.Open();
return true;
}
catch (Exception) //this is your first time ! so,learn to use “try catch” as available as possible! it’s very important!
{
return false;
}
}
There are two basic conditions on executing SQL command, first is query command (select * from [table_name]) , second is non-query command (insert,update,delete).
Here are the codes ;
// this is a method for executing query command
public void execQuery(string sql) {
OracleCommand cmd = new OracleCommand(sql);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
try
{
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//read the query result. On this example, i put three names of my database fields, there are “NAMA” ,”ALAMAT”,”EMAIL”
Console.WriteLine(Convert.ToString(reader["NAMA"]));
Console.WriteLine(Convert.ToString(reader["ALAMAT"]));
Console.WriteLine(Convert.ToString(reader["EMAIL"]));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
cmd.Dispose();
}
}
//this is a method for executing non-query command
public bool execNonQuery(string sql) {
OracleCommand command = new OracleCommand(sql);
command.Connection = conn;
try
{
//a non-query command doesn’t need any reader, all you have to do is execute them !
command.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}






please put a comment if this post is helpful ..
thanx
By: oliver indra prodinger on March 4, 2008
at 7:32 am
This is really great. I have always created SQL Server 2000/2005 DB connections and I would not have known that they are very similar to Oracle connections. Created a connection and executed query in no time and works perfectly. Now I can created an Oracle class for my library. One question though, wouldn’t you want to also dispose the connection or at least close it so resources are not sitting out there?
Thank You.
By: Aaron on March 19, 2008
at 6:08 pm
//to Aaron
hei,, take it easy man.. course I knew it..
I think I forgot that one, by the way, this post is for dummies after all… lets just say, “connection works, they’ll happy”
peace
By: oliver indra prodinger on March 21, 2008
at 12:48 pm
Nice Code. I need to connect to an oracle10g server on my network using C# and retrieve BLOBs [Photos] then save them to a file. how do i go about it? I have to retrieve about 600,000 photos and save them to file.
The table in the oracle database is called EMPRecords. it has the following fields; EMPID, FirstName, SurName, Photo
I want to save the images with the EMPID
Thanks.
By: Fikzy on April 7, 2008
at 7:23 am
//to Fikzy
I never used BLOBs in Oracle before, but I have experience using Image datatype in SQL Server 2005.
The very first thing you have to do is convert the Image type into byte[] type, you can google it for better explanation. Finally, you can insert this byte[] variable to your database. That’s it, all set !! Goodluck !
By: oliver indra prodinger on April 8, 2008
at 7:26 am
itz realy very good and helpin code….
By: Anish on January 19, 2009
at 4:53 am
how to physically add following components to a c# project :
1.oConnection
2.oDataAdapter
3.oCommand
4.reader
plz help we r stuck…
By: neha on February 5, 2009
at 6:16 am
thanks Oliver…code was very helpful n conn issue was resloved easily….thanks Mehshan for telling me about it:)
By: sabbi on June 14, 2009
at 8:56 pm
How to close an oracle connection using diferences forms?
By: Allan on July 27, 2009
at 8:40 pm
hey thanks yarr.. that is really gr8
By: ashish on November 25, 2009
at 8:14 am
Bagus sekali ya !! Thanks.
By: vijay on February 3, 2010
at 5:35 pm
This is an informative one…
I did a similar work too
nicely done!!
By: Mahmud on March 16, 2010
at 10:57 am
nice post
By: Bikash on March 19, 2010
at 1:17 pm
:::::::::::::::::::::::::::::::::
using System;
using System.Collections.Generic;
using System.Text;
using PRYDATA;
using System.Data;
namespace PryNegocio
{
public class ClsNegocio
{
Clsdata obj = new Clsdata();
//instanciando la clase Clsdata
public DataTable FacMes(int anio)
{
return obj.TraeTabla(“Spmes”, anio);
}
:::::::::::::::::::::::::::::::::::
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OracleClient;
using System.Configuration;
namespace PRYDATA
{
public class Clsdata
{
public String Conexion()
{
return ConfigurationManager.ConnectionStrings["conex"].ConnectionString;
}
//un metodo general para ejecutar cualquier procedure , pasando n parametros
public DataTable TraeTabla(string nompro, params object[] lista)
{
OracleConnection cn = new OracleConnection(Conexion());
OracleCommand cmd = new OracleCommand(nompro, cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
OracleCommandBuilder.DeriveParameters(cmd);
int cuenta = 0;
string parm;
foreach (OracleParameter pr in cmd.Parameters)
{
parm = pr.OracleType.ToString();//obtener el tipo de parametro
if (parm.ToUpper() != “CURSOR”)
{
pr.Value = lista[cuenta];
cuenta++;
}
}//fin foraech
OracleDataAdapter da = new OracleDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cmd.Dispose();
da.Dispose();
return dt;
}//fin traetabla
//funcion de ejecutar
public int Ejecuta(string nompro, params object[] lista)
{
OracleConnection cn = new OracleConnection(Conexion());
OracleCommand cmd = new OracleCommand(nompro, cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
OracleCommandBuilder.DeriveParameters(cmd);
int cuenta = 0;
foreach (OracleParameter pr in cmd.Parameters)
{
pr.Value = lista[cuenta];
cuenta++;
}//fin foraech
int res = cmd.ExecuteNonQuery();
cn.Close();
cmd.Dispose();
return res;
}//fin traetabla
//funcion de ejecutar
}
}
::::::::::::::::::::::::::
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using PryNegocio;
namespace PryPresentacion
{
public partial class Form1 : Form
{
ClsNegocio obj = new ClsNegocio();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.dataGridView1.DataSource = obj.FacMes(Convert.ToInt32(textBox1.Text));
}
}
}
By: eldavan on April 28, 2010
at 5:56 am
Thanks Budddy!!!!!!!!
By: Funda on September 2, 2010
at 2:47 am
What is SID? from where i can get this value? i cant use directly the server ip in connection string? Please urgent reply will be highly appreciated
By: mujib on November 13, 2010
at 9:18 am
[...] 2)simple oracle connection in C# (Oracle 10g & XE) private OracleConnection conn; public bool OpenConnection(string SID, string user, string password){ try { //instance new oracle connection conn = new OracleConnection(“Data Source=”+SID+ “; User Id=”+user+”; Password=”+password+”;”); //open the connection conn.Open(); return true; } catch (Exception) //this is your first time ! so,learn to use “try catch” as available as possible! it’s very important! { return false; } } [...]
By: C# – Database Connection « Prayag Upd on June 25, 2011
at 1:41 pm
Kindly tell me how to create a simple application of Oracle 10g with c++
By: Asad on December 5, 2011
at 7:02 am
Pretty easy code and I’m going to implement it
By: faisy on December 14, 2011
at 10:11 am