how do i access one record from query results in python

Question:

hi i have this query and its result i was trying to access record by record at a time but im not able to

select_migration_db = "SELECT B.rmt_n, A.prr_id, A.rp_ID FROM mo_TRAC A, T_sft_init_prr B WHERE A.rp_id=B.int_prr_id AND A.STATUS='Sc' AND A.PHASE='first' AND A.WAVE='first'"
def my_query(query,cursor):
    conn = oracle.connect(user=user,password=pwd,dsn = host,encoding="UTF-8")
    cursor = conn.cursor()
    return cursor.fetchall()

rows =my_query
for r in rows:
    print (r)
the table result looks like
rmt_n         prr_id          rp_ID       
                 
ss_tt_1        1456           767
rr_mm_2        663            889
ss_op_3        8894           999
Asked By: greeg

||

Answers:

select_migration_db = "SELECT B.rmt_n, A.prr_id, A.rp_ID FROM mo_TRAC A, T_sft_init_prr B WHERE A.rp_id=B.int_prr_id AND A.STATUS='Sc' AND A.PHASE='first' AND A.WAVE='first'"

    conn = oracle.connect(user=user,password=pwd,dsn = host,encoding="UTF-8")


with conn.cursor() as cursor:
            cursor.execute(select_migration_db)
            while True:
                row = cursor.fetchone()
                if row is None:
                    break
                print(row)
Answered By: Sikeh Japhet

You have lots of really basic errors:

  • You’re not calling the function with my_query(select_migration_db).
  • The function doesn’t need cursor to be a parameter
  • The function never executes the query
select_migration_db = "SELECT B.rmt_n, A.prr_id, A.rp_ID FROM mo_TRAC A, T_sft_init_prr B WHERE A.rp_id=B.int_prr_id AND A.STATUS='Sc' AND A.PHASE='first' AND A.WAVE='first'"

def my_query(query):
    conn = oracle.connect(user=user,password=pwd,dsn = host,encoding="UTF-8")
    cursor = conn.cursor()
    cursor.execute(query)
    return cursor.fetchall()

rows = my_query(select_migration_db)
for r in rows:
    print(r[0])
    input("are you ready for the next row?")

The function assumes you’ve set global variables user, pwd, and host appropriately for your Oracle connection.

Answered By: Barmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.