带有绑定字符串变量的Python cx_Oracle SQL

时间:2017-07-31 17:44:15

标签: python sql oracle

我在使用Python为Oracle数据库创建SQL查询时遇到问题。 我想绑定字符串变量,它不起作用,你能告诉我我做错了什么吗? 这是我的代码:

import cx_Oracle

dokList = []

def LoadDatabase():
    conn = None
    cursor = None
    try:
        conn = cx_Oracle.connect("login", "password", "localhost")

        cursor = conn.cursor()

        query = "SELECT * FROM DOCUMENT WHERE DOC = :param"

        for doknumber in dokList:

            cursor.execute(query, {'doknr':doknumber})
            print(cursor.rowcount)

    except cx_Oracle.DatabaseError as err:
        print(err)
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()

def CheckData():

    with open('changedNamed.txt') as f:
        lines = f.readlines()

        for line in lines:
            dokList.append(line)

CheckData()
LoadDatabase()

cursor.rowcount的输出为0,但应该是大于0的数字。

1 个答案:

答案 0 :(得分:1)

您为参数使用字典({'doknr' : doknumber}),因此它是命名参数 - :param needs to match the key name。试试这个:

query = "SELECT * FROM DOCUMENT WHERE DOC = :doknr"
for doknumber in dokList:
        cursor.execute(query, {'doknr':doknumber})
        print(cursor.rowcount)

为了将来的问题排查,要检查您的参数是否正常通过,您还可以尝试将查询更改为"select :param from dual"