cx_oracle从CSV读取

时间:2017-11-29 18:34:43

标签: python oracle csv cx-oracle

我有一个cx_oracle连接,我希望运行'批量'尝试从CSV文件中收集姓氏的ID。下面我有我的代码,其中我得到一个cx_Oracle.DatabaseError:ORA-01756:引用字符串没有正确终止错误。

指向

and spriden_change_ind is null'''.format(lname,fname)

但是我知道这是有效的,因为你会看到我的注释代码以这种方式使用格式,它工作得很好。 rows_to_dict_list是我前面找到的一个很好的函数,基本上将列名添加到输出中。

任何方向都会很好!谢谢

import csv, cx_Oracle

def rows_to_dict_list(cursor):
    columns = [i[0] for i in cursor.description]
    new_list = []
    for row in cursor:
        row_dict = dict()
        for col in columns:
            row_dict[col] = row[columns.index(col)]
        new_list.append(row_dict)
    return new_list

connection = cx_Oracle.connect('USERNAME','PASSWORD','HOSTNAME:PORTNUMBER/SERVICEID')
cur = connection.cursor()
printHeader = True
with open('nopnumber_names.csv')as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        lname = row['Last']
        fname = row['First']
        cur.execute('''select spriden_pidm as PIDM,
                     spriden_last_name as Last,
                     spriden_first_name as First,
                     spriden_mi as Middle,
                     spriden_ID as ID
                     from spriden
                     where upper(spriden_last_name) = '{0}'
                     and upper(spriden_first_name) = '{1}'
                     and spriden_change_ind is null'''.format(lname,fname)
                    )

        # THIS RECORD RUNS FINE
        # cur.execute('''select spriden_pidm as PIDM,
        #              spriden_ID as ID,
        #              spriden_last_name as Last,
        #              spriden_first_name as First
        #              from spriden
        #              where spriden_pidm = '{}'
        #              and spriden_change_ind is null'''.format(99999)
        #             )


data = rows_to_dict_list(cur)
for row in data:
     print row
cur.close()
connection.close()

1 个答案:

答案 0 :(得分:1)

我最好的猜测是,CSV文件中某处的名字或姓氏中包含'个字符。

你真的不应该通过连接字符串或使用字符串格式来构建SQL。如果您这样做,您将面临SQL injection 的风险。如果有人在姓氏为X' OR 1=1 --的CSV文件中添加了记录,会发生什么?

而是使用绑定参数将变量的值发送到数据库。请尝试以下方法:

        cur.execute('''select spriden_pidm as PIDM,
                     spriden_last_name as Last,
                     spriden_first_name as First,
                     spriden_mi as Middle,
                     spriden_ID as ID
                     from spriden
                     where upper(spriden_last_name) = :lname
                     and upper(spriden_first_name) = :fname
                     and spriden_change_ind is null''',
                     {"lname": lname, "fname": fname}
                    )