gpt4 book ai didi

python - 传递 python list oracle where 子句 cx_Oracle

转载 作者:行者123 更新时间:2023-11-28 17:26:55 25 4
gpt4 key购买 nike

尝试将 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

关于python - 传递 python list oracle where 子句 cx_Oracle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38119700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com