Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从oracle查询输出中生成列表_Python_List_Cx Oracle_Strip - Fatal编程技术网

Python 如何从oracle查询输出中生成列表

Python 如何从oracle查询输出中生成列表,python,list,cx-oracle,strip,Python,List,Cx Oracle,Strip,我试图从oracle查询输出中列出一个列表。该列表将进一步用于绘制图表。 我无法从查询输出中生成一个干净的列表。请建议 """ Created on Sat Sep 21 11:36:10 2019 @author: Pitanshu """ # import modules import cx_Oracle # database connection user=input('Enter the user for database : ') passwd=input('enter the p

我试图从oracle查询输出中列出一个列表。该列表将进一步用于绘制图表。 我无法从查询输出中生成一个干净的列表。请建议

"""
Created on Sat Sep 21 11:36:10 2019

@author: Pitanshu
"""
# import modules
import cx_Oracle

# database connection
user=input('Enter the user for database : ')
passwd=input('enter the password for the above user : ')
conn_str=user+'/'+passwd+'@localhost/orcl'
conn=cx_Oracle.connect(conn_str)

# creation of cursor
cursor=conn.cursor()
cur=cursor.execute('select distinct emp_name from employee')

employee=[]

col_names = [row[0] for row in cursor.description]
print(col_names)

for i in cur:
    employee.append(i)

print(employee)    

#closing cursor and connection
cursor.close()
conn.close()
收到的输出:

Enter the user for database : system
enter the password for the above user : ********
['EMP_NAME']
[('e',), ('d',), ('a',), ('b',), ('c',)]
预期产出:

Enter the user for database : system
enter the password for the above user : ********
['EMP_NAME']
['e','d','a','b','c']

只需将等效行更改为:

for i in cur:
    employee.append(i[0]) #for python newbies, getting the only element in the list could also be done with: i[-1] or next(iter(i)) or operator.itemgetter(0)(i) or operator.itemgetter(-1)(i) or i.pop() or i.pop(0) or i.pop(-1)
其背后的逻辑是: 查询关系数据库表时,您将得到行(在本例中为列表形式)作为回报。因此,即使您希望每行只包含一列,您也会得到每行包含一个元素的列表,而不是元素本身


作为命名约定,在命名列表时,您可能希望使用
employees
而不是
employees

更简单:
employees=[i代表i,以cur为单位]