Search code examples
c#.netoracle-sqldeveloperodp.netodp

ODP.NET Implement Cursor for SELECT statement


How can I implement a simple cursor fetch on a basic SELECT statement like 'SELECT * FROM Employees' using ODP.NET?


Solution

  • So it's quite straightforward.

    First create OracleConnection class like this

    OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString);
    
    con.Open();  //opens connection
    

    Then you define and OracleCommand instance first by passing either raw query/stored procedure as first argument like

    So in your particular case it would be OracleCommand cmd = new OracleCommand("SELECT * FROM Employees", con

    if (con.State == ConnectionState.Open)
    {
    using (OracleCommand cmd = new OracleCommand(<query>/<stored proc>, con))
    {    
    cmd.CommandType = CommandType.StoredProcedure;  //in case of stored proc
    cmd.BindByName = true;
    
    OracleDataReader reader;
    try
      {
        reader = cmd.ExecuteReader();    
        while(reader.Read())
        {
            Console.WriteLine("field: {0}", reader.GetDecimal(0));  
        }    
      }
    catch (OracleException e)
      {
      foreach (OracleError err in e.Errors)
        {
           //print errors         
         }
       }
     con.Close(); 
     con.Dispose();
    }
    }
    

    Here is the example http://www.oracle.com/technetwork/articles/dotnet/williams-refcursors-092375.html