繁体   English   中英

传递python list oracle where子句cx_Oracle

[英]Passing python list oracle where clause cx_Oracle

我很沮丧,试图将Python列表传递给Oracle WHERE子句。 我正在使用cx_Oracle,这是我的代码:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import cx_Oracle

con = cx_Oracle.connect(str('user/passwordr@server/orcl'))
cursor = con.cursor()
ids = [19 , 87 , 84]
cursor.execute(str("select  employee_id , first_name , last_name from employees  where employee_id in ('"+ids+"')" ))
people = cursor.fetchall()
print people

'''The following code works for me , but the problem is the string formater placeholer is not gonna be static is dynamic.'''
params = (198 , 199)
cursor.execute(str("select  employee_id , first_name , last_name from employees  where employee_id in ('%s' , '%s')" %(params)))

'''Also it would be valid if i can create dynamically the string formater placeholder depending on "length of something".
Sorry if this question was answered i spend hours searching the solution , but i do not found it.'''

经过几个小时试图找出如何做到这一点,我终于得到了解决方案。 这是代码:

# -*- coding: utf-8 -*-
#from __future__ import unicode_literals
import cx_Oracle
con = cx_Oracle.connect(str('user/pass@server/orcl'))

cursor = con.cursor()

cursor.execute(str('select employee_id from employees where rownum < 3 '))

desc = [d[0] for d in cursor.description]
resutl = [dict(zip(desc,line)) for line in cursor]

ids = []
for i in range(len(resutl)):
    ids.append(resutl[i]['EMPLOYEE_ID'])

placeholders = ','.join(":x%d" % i for i,_ in enumerate(ids)) 

sql = """SELECT job_id
         FROM job_history
         WHERE employee_id IN (%s)""" % placeholders 

cursor.execute(sql,ids ) 
rs =  cursor.fetchall() 

print rs

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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