Posted by: oliver indra prodinger | August 18, 2007

simple oracle connection in C# (Oracle 10g & XE)

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;
}

}


Responses

  1. please put a comment if this post is helpful ..

    thanx

  2. 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.

  3. //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 :)

  4. 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.

  5. //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 !

  6. itz realy very good and helpin code….

  7. how to physically add following components to a c# project :
    1.oConnection
    2.oDataAdapter
    3.oCommand
    4.reader
    plz help we r stuck…

  8. thanks Oliver…code was very helpful n conn issue was resloved easily….thanks Mehshan for telling me about it:)

  9. How to close an oracle connection using diferences forms?

  10. hey thanks yarr.. that is really gr8

  11. Bagus sekali ya !! Thanks.

  12. This is an informative one…
    I did a similar work too :D
    nicely done!!

  13. nice post

  14. :::::::::::::::::::::::::::::::::
    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));

    }
    }
    }

  15. Thanks Budddy!!!!!!!!

  16. 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

  17. [...] 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; } } [...]

  18. Kindly tell me how to create a simple application of Oracle 10g with c++

  19. Pretty easy code and I’m going to implement it :)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.