简体   繁体   中英

Python :- How to store query result data into an array and access each element by Index number

I want to store data in a array variable say path_list and to store all the states into this array. And when i print path_list [0] it should print 'MSF' or when i print path_list [2] it should print 'MIF' But currently all the result is getting stored into a tuple and it is not getting printed when i use print in the for loop. However, when i printing it outside of loop it is working. Please suggest me any way

My table structure is like

STATE    TOC      ID      NUMBER
MSF   MSPROFMSV 465984  5926987700
MSF   MSPROFMSV 465977  5926063400
MIF   MIPROFMSV 465977  5926063100
MIF   MIPROFMSV 465977  5926063900

Code:-

import cx_Oracle
import shutil
import os
import logging
import time
import re
timestr = '_'+time.strftime("%Y%m%d-%H%M%S")    
conn = cx_Oracle.connect(user=r'lsaxena2/Dec2*19k@ed03:1521/encdv03svc.uhc.com') 
cur_path = conn.cursor()
cur_file = conn.cursor()
cur_path.execute('select distinct state from E0572476.ENSUBAPP_config order by state') 
path_exec = cur_path.fetchall()
i=0
path_list = []
print (path_exec[1][0])
while i < len(path_exec):
   path_list = path_exec[i][0]
   print (path_list[i])    
   i = i+ 1

SQL generates rows, which are always tuples. Since cr.fetchall fetches all results, you're getting a list of rows = a list of tuples. Even if you only have one value, it's a 1-uple.

So you just need to extract the one value from your tuple and move it to the output list:

path_list = [row[0] for row in path_exec]

Incidentally your naming scheme is awful. And I don't understand why you have two cursors, or why you never close them

import cx_Oracle
import time

timestr = '_'+time.strftime("%Y%m%d-%H%M%S")

with cx_Oracle.connect(user=r'lsaxena2/Dec2*19k@ed03:1521/encdv03svc.uhc.com') as conn,\
     conn.cursor() as cr:
    cr.execute('select distinct state from E0572476.ENSUBAPP_config order by state') 
    states = [state for [state] in cr.fetchall()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM