Cx_Oracle cursor - return named tuple

Hello All,
I'm having trouble figuring a way to convert the row returned from a basic execute statement into a named tuple/Dictionary.
The idea, is to be able to access each field via row['column_name']. I'm currently looking at creating a factory, but still a complete noob to python and cx_Oracle.
cur.execute(""SELECT * FROM V$INSTANCE""")
#print 'Query Executed..'
row = cur.fetchone()
#print 'Cursor Loaded.'
#print result[0], result[1]
list = {}
list['host_name'] = row['host_name']
print row['host_name']
Thanks in advance for your assistance.
Jan S.

Hello All,
Managed through some weird keyword search to find a nice little article. here is the solution.
cur = oracle.cursor()
cur.execute("""SELECT * FROM V$DATABASE""")
data = rows_to_dict_list(cur)
for row in data:
print row['PROTECTION_LEVEL']
def rows_to_dict_list(cursor):
columns = [i[0] for i in cursor.description]
return [dict(zip(columns, row)) for row in cursor]
Thanks
Jan S.
ps - I hate these new editors, Python requires indentations, but that does not mean I want to create and html table from it.

Similar Messages

  • How to find if cursor returned rows

    If i have a procedure like
    create procedure test as
    cursor cur_test is
    select col
    from table;
    begin
         delete from tab1 a;
         for var_cur_test in cur_test
         loop
              insert into temp
              values(var_cur_test.col);
         end loop;
         commit;
    end;
    How do I check if the cursor has returned any rows?
    I dont want to delete from tab1 if cursor 'cur_test' does not return any rows and I want to exit out of the proc.
    If the cursor returns rows > 0 then I want to delete and do the insert.
    Thanks for the help.

    The scenario is like this.
    There is a schema A which has to run a process and populate its tables and at the end of the process(java program) run the procedure which is in schema B to pull data from schema A and populate the tables in schema B. If there is a case where Schema A's process fails( then Schema A's tables end up with no data), the process is still running the procedure in schema B and deleting the data in tables with no data being inserted.
    So, I have to check in the procedure if the tables in Schema A have any data before the process can run the proc.
    I tried the solution you provided but it returns no data
    CREATE OR REPLACE PROCEDURE MMA_TEST
    VAR_CONTRACT_ID VARCHAR2
    AS
    CURSOR CUR_TEST IS
    SELECT CMS_CONTRACT_ID,CMS_PLAN_ID
    FROM MMA_PLANS
    WHERE CMS_CONTRACT_ID = VAR_CONTRACT_ID;
    BEGIN
         for var_cur_test in cur_test
         loop
              if (cur_test%rowcount = 1) then
              delete from temp ;
              end if ;
              insert into temp
              values(var_cur_test.cms_contract_id,var_cur_test.cms_plan_id);
         end loop;
    end;

  • Creating a function having a ref cursor returned

    I get an error message for the following code below. I am trying to create a function that allows the users to pass in a certain parameter which is used to invoke a specific query for the paramented passed in. Once the query is invoked, it should return a ref cursor. Please help. I am still using pl/Sql developer.
    create or replace package TEST2 is
    type rec_DropDownList_Item is RECORD(
    TEXT_TYPE VARCHAR2(200),
    xsVALUE VARCHAR2(200));
    TYPE cur_DropDownList IS REF CURSOR RETURN rec_DropDownList_Item;
    FUNCTION Getprocedure_yearreportdisplay (need_type in VARCHAR2) RETURN cur_DropDownList;
    end TEST2;
    create or replace package body TEST2 is
    FUNCTION Getprocedure_yearreportdisplay (need_type in VARCHAR2)
    RETURN cur_DropDownList IS
    my_ref_cursor cur_DropDownList;
    BEGIN
    OPEN my_ref_cursor FOR
    SELECT vehicletype, vehicledescription
    FROM cars where vehicletype = need_type;
    return my_ref_cursor;
    END Getprocedure_yearreportdisplay;
    end TEST2;

    user13046875 wrote:
    a simple example might help because I am having a difficult understanding the reply. Thank you.
    create or replace package TEST2 is
       type rec_DropDownList_Item is RECORD(
       TEXT_TYPE VARCHAR2(200),
       xsVALUE VARCHAR2(200));
       TYPE cur_DropDownList IS REF CURSOR RETURN rec_DropDownList_Item;
       FUNCTION Getprocedure_yearreportdisplay (need_type in VARCHAR2) RETURN cur_DropDownList;
    end TEST2;
    create or replace package body TEST2 is
    FUNCTION Getprocedure_yearreportdisplay (need_type in VARCHAR2)
    RETURN cur_DropDownList IS
    my_ref_cursor cur_DropDownList;
    BEGIN
       OPEN my_ref_cursor FOR
       SELECT 'column1', 'column2'
       FROM dual;
       return my_ref_cursor;
    END Getprocedure_yearreportdisplay;
    end TEST2;
    TUBBY_TUBBZ?variable x refcursor;
    TUBBY_TUBBZ?
    TUBBY_TUBBZ?exec :x := TEST2.Getprocedure_yearreportdisplay('dummy');
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.01
    TUBBY_TUBBZ?print :x
    'COLUMN 'COLUMN
    column1 column2
    1 row selected.
    Elapsed: 00:00:00.03
    TUBBY_TUBBZ?Is an example of running in SQLPLUS (you may want to get your own copy, it's free and available on OTN).

  • How to read my cursor that is ref cursor returning user defined type

    Hi
    I have types defined as follows:
    TYPE MY_RECORD IS RECORD (
    COL1 TABLE1.COL1%TYPE,
    COL2 TABLE1.COL2%TYPE
    TYPE MY_CURSOR IS REF CURSOR
    RETURN MY_RECORD;This is used as return type in a stored procedure.
    I have a pl/sql block where I make a call to the SP that returns this cursor.
    How can I read individual values being returned from SP?

    SQL> create or replace package pkg
    as
       type my_record is record (col1 emp.empno%type, col2 emp.ename%type);
       type my_cursor is ref cursor
          return my_record;
       procedure p (cur out my_cursor);
    end pkg;
    Package created.
    SQL> create or replace package body pkg
    as
       procedure p (cur out my_cursor)
       as
       begin
          open cur for
             select   empno, ename
               from   emp
              where   rownum <= 2;
       end p;
    end pkg;
    Package body created.
    SQL> declare
       cur     pkg.my_cursor;
       e_rec   pkg.my_record;
    begin
       pkg.p (cur);
       loop
          fetch cur into   e_rec;
          exit when cur%notfound;
          dbms_output.put ('Empno: ' || e_rec.col1);
          dbms_output.put_line ('; Ename: ' || e_rec.col2);
       end loop;
       close cur;
    end;
    Empno: 7369; Ename: SMITH
    Empno: 7499; Ename: ALLEN
    PL/SQL procedure successfully completed.

  • What is a good way to check if sql select basd cursor return anything

    Hello everyone,
    I am trying to find a good way to identify that a SQL select based cursor return nothing.
    I know that or we use exception when no data found, or count(*) to check how many rows are returned.
    I have a cursor based on quite a long select statement.
    Like
    CREATE OR REPLACE PROCEDURE aaa (v_input IN NUMBER, v_output OUT VARCHAR2)
         CURSOR long_cursor IS
              --long select statement(with input variable) ;
    BEGIN
         Select count(*)
         Into v_count
      From
      -- a long select statment with input again ;
      IF v_count > 0 then
        For record in long_cursor loop
         --Get information from cursor
            --other processing for output
        End loop;
      END IF;
    END;Is there any other way than the above ?
    I would love to reduce the amount of typing. I know that repetition in code is not good.
    Thanks in advance,
    Ann
    Edited by: Ann586341 on Feb 28, 2013 2:29 PM

    >
    Not sure I understand your point. I am still a new bie here.
    >
    A flag is just a piece of data. By itself it doesn't prevent anyone from changing the data. And in a multiuser system anything you try to check is based on the COMMITTED data in the system. Two users can be changing two different rows at the same time but neither user will see the other change.
    So if you try to count how many rows meet a particular condition you may get a count of 8 but after the other user commits the count might be 7 or 9. So if you use 8 it may not be valid for very long.
    >
    But the app we use is Oracle Application Express 4.0.
    I assume when the data is read, there will be some kind of lock on these rows so other users cannot change it, right ?
    Or should I use SELECT for update even I do not update anything here.
    >
    I can't help you with that one. That would be a question for the application express forum.
    Oracle Application Express (APEX)
    You don't need to use FOR UPDATE if you don't plan to change the data. But, as explained above, you can't rely on any data you query being the same because another user could be changing it while you are looking at it.

  • Ref cursor returns login ids

    I have this ref cursor that returns login ids from a procedure.
    While I can define the ref cursor as sys_refcursor; I want to use strongly typed ref cursor ( for improved readabilty of code).
    But I guess I can not define the cursor that returns %type.
    e.g. Type return_login_id IS REF CURSOR return tab1.login_id%type;
    On compilation the package threw an error saying the return type should be record.
    I need to define a record with one column and use that as return type ?
    any other way around ?
    TIA
    S

    Btw, why you need to use REF Cursor?
    You can use just a cursor:
    SQL> declare
      2  cursor c1 is select empid from emp;
      3  TYPE my_id IS TABLE OF emp.empid%type;
      4  myid my_id := my_id();
      5  BEGIN
      6  OPEN c1;
      7  FETCH c1 BULK COLLECT INTO myid;
      8  CLOSE c1;
      9  END;
    10  /
    PL/SQL procedure successfully completed.
    SQL>

  • Ref cursor return type

    i am using a ref cursor as out parameter in a stored procedure.
    When I call the stored procedure and want to retrieve the rows returned by the ref cursor,
    is there a way to fetch the records using something like %ROWTYPE if I donot know the type of rows returned by the cursor.
    eg.
    procedure my_test_ref_cursor ( a OUT SYS_REFCURSOR) IS
    BEGIN
    OPEN a FOR SELECT EMP_ID, EMP_NAME FROM EMP;
    END;
    procedure call_my_test_ref_cursor is
    b sys_refcursor;
    begin
    my_test_ref_cursor(b);
    fetch b into XXXXXXX - if this program doesnot know the type of ref cursor 'b' is pointing to is there a way to use
    something like %ROWTYPE here ?
    end;

    While you can use the logic to return a weakly typed reference cursor, there should be a compelling why. A strongly typed reference cursor may be a better solution. You define a strongly typed reference cursor inside a package, and you anchor it to a ROWTYPE. Weakly typed reference cursors are typically useful when you are working with a subset of a table because you can't anchor to part of a table. However, you can define a view that uses the portion of the table and anchor a strongly typed reference cursor to the view.
    A strongly typed PL/SQL reference cursor is defined like this in a package specification:
    TYPE strongly_typed_cursor IS REF CURSOR RETURN some_table%ROWTYPE;
    So, if you rewrote it like this ...
    PROCEDURE my_test_ref_cursor (a OUT SOME_PACKAGE.STRONGLY_TYPED_CURSOR) IS
    BEGIN
    OPEN a FOR SELECT emp_id, emp_name FROM emp;
    END;
    Now, you can access it like this ...
    PROCEDURE call_my_test_ref_cursor IS
    another_var SOME_PACKAGE.STRONGLY_TYPED_CURSOR;
    target SOME_TABLE%ROWTYPE;
    BEGIN
    my_test_ref_cursor(another_var);
    LOOP
    FETCH another_var INTO target;
    EXIT WHEN another_var%NOTFOUND;
    dbms_output.put_line('See it '||target.emp_name||'.');
    END LOOP;
    END;
    The DBMS_SQL method you're looking for is Method 4. My recollection is that there isn't a good example in the docs but I could be wrong ... The OCI works no differently, nor does the JDBC interface. Hope this helps.

  • Field validation with cursor returning on the field in error.

    Hi,
    Is there a way to return the cursor to a specific INPUT field on an alv grid after a validation return an error on it?
    Thanks.

    Hi,
    Try using the method SET_CURRENT_CELL_VIA_ID..
    Please check this thread..
    Re: Can we scroll to the last page of an alv grid?
    Thanks
    Naren

  • When I hit return after typing, the cursor returns to the beginning of the sentence

    I open a new layer.
    I type my text
    I hit return'
    The cursor starts typing at the beginning of the sentence, typing right over the text I just finished.  It will not go to the next line.  I've been using PS since 2 and I have never seen this nor do I know what to do about it.
    Help...
    Thanks

    starbird parrot wrote:
    Thank you.  I had no idea.  I do not believe I have ever touched that or even seen it.  I don't do a lot of text, I'm a photographer. Nor do I know what a leading value is...
    There are all sorts of gotchas in the Character panel.  That line of  T T TT Tt  at the bottom produce faux styles, for instance, so if you find all your text is capitalized, or strikethrough, you'll know where to look.  You'll notice I had vertical scale set to 118%?  Well I had forgotten that was set that way, and I will have been laying out distorted text because of it!  Purists frown upon changing a fonts aspect ratio that way, because it spoils a carefully designed font — they would say to find the right font for the job.  That is much easier than it used to be now we have TypeKit with its useful, and much appreciated filters.  Also be aware of the anti-aliasing at the bottom right corner, and also on the options bar when the Type tool is selected.  I think some users go years without realizing that is there, and then wonder why their text is all jagged.
    If you have a Lynda.com subscription, Nigel French has an excellent title called Photoshop for Designers — Type Effects.  Nigel also has a nice British accent, and a lot easier to listen to than some Lynda.com presenters.
    Watch the Online Video Course Photoshop for Designers: Type Effects
    Nigel has a whole raft of Lynda.com titles

  • Cursors returned from a package

    Ok, I've done this a long time ago but how do I get a package to return a cursor?
    Here's my spec...
    CREATE OR REPLACE PACKAGE reservationhistory AS
    TYPE ResType IS RECORD
                   (resid integer,
                   status varchar2(2));
    PROCEDURE getHistory(i_providerid in integer,
         resdetail in out ResType,
         o_error_code out varchar2);
    END reservationhistory;
    Here's my attempt at the body...
    CREATE OR REPLACE PACKAGE BODY reservationhistory AS
    PROCEDURE getHistory(i_providerid in integer,
              resdetail in out ResType,
              o_error_code out varchar2) IS
    BEGIN
    OPEN resdetail FOR
                   select bookingid resid, status, providerid from booking
                   where providerid = i_providerid;
              o_error_code := 0;
    END getHistory;
    END reservationhistory;
    But it doesn't like this.
    What am I missing???
    Thanks,
    Todd

    Thanks, I tried that and but it still doesn't work. The following code gives me this error:
    LINE/COL ERROR
    10/9 PLS-00306: wrong number or types of arguments in call to
    'RESDETAIL'
    10/9 PL/SQL: SQL Statement ignored
    Here's the code...
    CREATE OR REPLACE PACKAGE reservationhistory AS
    TYPE ResType IS ref cursor;
    PROCEDURE getHistory(i_providerid in integer,
         resdetail in out ResType,
         o_error_code out varchar2);
    END reservationhistory;
    CREATE OR REPLACE PACKAGE BODY reservationhistory AS
    PROCEDURE getHistory(i_providerid in integer,
              resdetail in out ResType,
              o_error_code out varchar2) IS
    BEGIN
    OPEN resdetail FOR
                   select bookingid resid, status, providerid from booking
                   where providerid = i_providerid;
              o_error_code := 0;
    END getHistory;
    END reservationhistory;
    I appreciate your help on this.

  • Why does the cursor return to the top of the screen?

    The cursor starts at the top of the screen and returns there no matter where I drag it. It never goes past the middle of the screen. It works fine in safe mode. Same problem with all mice(tried 2 Bluetooth and one USB). I deleted Magic Prefs...no change. iMac 24, Mountain Lion, 2 monitors. This has been running solidly for 6 months.

    Some more notes; this appears to be an issue if one of two things is true; the movie window is open - or - if I'm zoomed in too far (what the threshold is, I'm not sure.) I'm trying to automate dialog. In one instance, I need to adjust a cough; if I zoom in close enough to draw the automation, it returns the play head to bar one after each click. If I'm zoomed out a little bit, I can write the automation no problem.

  • I need to know how many  lines a cursor returns

    Hi,
    I need to know how many lines a cursor will return without counting it within a loop or putting a count clause within the cursor . Is there a way to do ?

    Please post this question in the database forum for an appropriate response: General Database Discussions
    Regards,
    OTN

  • Pro*C program to use a REF CURSOR returned by a DB Function

    Hi,
    Please help me with this.
    I have a pro*c program that should call a
    database function which returns a ref cursor.
    This is the sample code i have :-
    EXEC SQL BEGIN DECLARE SECTION;
    SQL_CURSOR emptycabin_cursor;
    int cabinid;
    EXEC SQL END DECLARE SECTION;
    EXEC SQL ALLOCATE :emptycabin_cursor;
    EXEC SQL EXECUTE BEGIN
    :emptycabin_cursor:=posremptycabin(:voy,:segid);
    END;END-EXEC;
    /* more_records = 1*/
    while (more_records)
    EXEC SQL FETCH :emptycabin_cursor INTO :cabinid;
    if (SQLCODE==NOTFOUND)
    {more_records=FALSE;break;}
    EXEC SQL close :emptycabin_cursor;
    When I execute I keep getting fetch out of sequence error.
    Can someone let me know whats wrong with this code?
    When I execute the function from sqlplus
    variable ref_cur refcursor ;
    exec :ref_cur:=posremptycabin(232,'CC');
    print :ref_cur;
    I get the data properly displayed.So nothing wrong with the function.
    Thanks for your help

    I know nothing about Pro*C, but Tom Kyte's Pro*C example for ref cursors fetches the cursor with a loop that looks like:
    for( ;; )
            EXEC SQL WHENEVER NOTFOUND DO break;
            EXEC SQL FETCH :my_cursor INTO :ename, empno;
            printf( "'%.*s', %d\n", ename.len, ename.arr, empno );
        EXEC SQL CLOSE :my_cursor;http://asktom.oracle.com/~tkyte/ResultSets/index.html
    Hope this helps.

  • Locking a cursor to named plot

    I am trying to lock a named cursor to a named plot. If I don't have a name for the cursor and leave the numerical index, the cursor will "lock to plot". If I use a property node to assign a cursor name, then all of the plots lock to the last cursor name.
    I set up the properties in the cursor list before the name is applied to the cursor.

    hello,
    I dont know if it is exactly what ou want to. I have done an example using property node to associate a cursor with a plot. Tell me if it is what you want to.
    Hope this help.
    Isabelle Jean
    Isabelle
    Ingénieur d'applications
    National Instruments France
    Attachments:
    cursor.vi ‏37 KB

  • At end of timeline cursor returns to beginning and starts over?

    I am sure there is an easy fix to this very minor issue.
    When I get to the end of any timeline the cursor automatically jumps back to the beginning and starts over.
    How do I get it to just stop at the end of the timeline?
    It used to stop and just started doing this somewhow? To my knowlege I have not made any changes to sequence settings, user preferences, etc.
    Many Thanks,
    Peter Mallamo

    If it was a snake it would have bit me!
    Thanks Michael. I guesss I somehow hit control L.
    Thanks again,
    PM

Maybe you are looking for

  • Downloading Adobe Flash Player Problem

    When I attempt to dowload the flash player I get a window of four possible problems that I might encounter with the download and that is all that happens. What is causing this to occur.  I need to download the flash player, but this window stops any

  • Sleek Photo 20gb MAJOR probl

    First off let me say that I can't even believe I have to come here to see how others are handling the problems with their players, I thought I found a player that was going to be a fantastic purchase. I was wrong. My player is less than a month old.

  • Can I use my MacMini install disks to reinstall on my iMac?

    I'm trying to use Boot Camp so I can create a 60GB partition on my iMac and install Win 7. However, I'm getting the infamous error about not being able to move files. So, it appears my only remedy is to wipe the internal drive on the iMac and reinsta

  • SSO of EP

    Hi, I have ERP landscape of DEV, QAS and PRD. Its ECC 6.0. I have EP landscape as QAS and PRD configured SSO and datasource as beckend ERP QAS and PRD systems respectively I had an requirement of EP DEV too. I made a system copy of QAS server as EP D

  • JSP Tags in JSPX

    I have been using jsp tags (.tag) in my JSF-JSPs to reuse components. As I have seen, Oracle recommends using .jspx instead of .jsp, so in my way to create a new application using jspx I found that I can not make the jsp tag work (using jspx and tagx