【问题标题】:Python3 : How to escape special characters for cx_oracle continuous stream of insert statement (ORA-01756: quoted string not properly terminated)Python3:如何为 cx_oracle 连续插入语句流转义特殊字符(ORA-01756:引用的字符串未正确终止)
【发布时间】:2020-12-27 01:37:05
【问题描述】:

我正在使用 python 代码读取 CSV 文件以及它在 Oracle 数据库中插入的每一行。

是否有办法克服所有用例的“ORA-01756:引用的字符串未正确终止”错误。

我想转义的特殊字符是单引号 (')、双引号 (")、逗号 (,) 和其他可能导致错误的字符。

我的逻辑其实如下:

    with open(files, newline='',  encoding='utf-8') as csvfile:
        rowreader = csv.reader(csvfile, delimiter=';', quotechar='|')
        next(rowreader)
        for row in rowreader:
            values = parseCSV.input(row)
            query = "INSERT INTO MYTABLE(col1,col2) values('{val1}','{val2}')".format(**values)
            cursor.execute(query)

以上不适用于要插入的字符串 - '我的名字'

【问题讨论】:

    标签: python sql python-3.x oracle11g cx-oracle


    【解决方案1】:

    documentation 中有一个示例,它比为每一行调用 execute() 快很多:

    import cx_Oracle
    import csv
    
    . . .
    
    # Predefine the memory areas to match the table definition
    cursor.setinputsizes(None, 25)
    
    # Adjust the batch size to meet your memory and performance requirements
    batch_size = 10000
    
    with open('testsp.csv', 'r') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        sql = "insert into test (id,name) values (:1, :2)"
        data = []
        for line in csv_reader:
            data.append((line[0], line[1]))
            if len(data) % batch_size == 0:
                cursor.executemany(sql, data)
                data = []
        if data:
            cursor.executemany(sql, data)
        con.commit()
    

    【讨论】:

      【解决方案2】:

      是的——使用参数/绑定。

      通过cx_oracle manual on using binds

      # assuming `values` is a dict with `val1` and `val2`:
      cursor.execute("INSERT INTO MYTABLE (col1, col2) values(:val1, :val2)", values)
      

      还要注意手册页是如何说“永远不要这样做!!!”了解如何将数据插入语句 - 您的代码目前也容易受到 SQL 注入攻击。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-09
      • 2022-01-12
      • 1970-01-01
      • 2010-11-12
      • 2019-03-09
      • 2019-07-22
      相关资源
      最近更新 更多