【问题标题】:Zero-length delimiter error using python psycopg2 to insert csv data into a postgres database使用 python psycopg2 将 csv 数据插入 postgres 数据库的零长度分隔符错误
【发布时间】:2020-11-23 20:52:29
【问题描述】:

我正在尝试使用 psycopg2 将一些 csv 文件的内容加载到我的 postgres 数据库中。当我运行脚本时,我收到以下错误:

psycopg2.errors.SyntaxError:零长度分隔标识符位于或 """"附近

(photo of traceback here)

我了解该错误很可能是由于 'example' 的空字符串值周围的单引号引起的,但我不知道这会导致问题的原因。

        df = pandas.read_csv(cip_location, header=0, encoding='ISO-8859-1', dtype=str)
        number_loaded_rows += len(df.index)
        for index, row in df.iterrows():
            row = row.squeeze()

            cip_code = row['CIPCode']
            cip_code = cip_code[cip_code.find('"') + 1:cip_code.rfind('"')]
            if cip_code.startswith('0'):
                cip_code = cip_code[1:]
            cip_title = row['CIPTitle']
            cip_def = row['CIPDefinition']

            exam_string = row['Examples']
            exam_string = exam_string.replace('Examples:', '').replace(' - ', '').replace(' -', '')
            examples = exam_string

            cip_codes[cip_code] = {
                'code': cip_code,
                'title': cip_title,
                'definition': cip_def,
                'examples': examples
            }

        with gzip.GzipFile(ending_location, 'r') as f:
            bytes = f.read()
            string = bytes.decode('utf-8')
            loaded_unis = jsonpickle.decode(string)
        print('Finished loading in ' + str(time.time() - start_load))

        import psycopg2

        cnx = psycopg2.connect('host=localhost dbname=postgres user=postgres password=password')
        count = 0
        cursor = cnx.cursor()
        for d in cip_codes.values():
            print('Inserted: %s' % count)
            print('Trying to insert (%s, "%s", "%s", "%s");' % (d['code'], d['title'], d['definition'], d['examples']))
            cursor.execute('CALL InsertCIP(%s, "%s", "%s", "%s");' % (str(d['code']), d['title'].replace('"', "'"),
                                                                      d['definition'].replace('"', "'"),
                                                                      d['examples'].replace('"', "'")))
            count = count + 1
        cnx.commit()
        cursor.close()
        cnx.close()

【问题讨论】:

    标签: python django postgresql psycopg2 delimiter


    【解决方案1】:

    Gzip 代码似乎没有在此处执行任何与 sql 相关的操作。

    在这种情况下,您的数据中的第一行似乎是空的,并且转义导致第 4 列数据为“”“”

    尝试让 psycopg2 为您进行转义。 如果您有大量数据,excute_batch 比遍历每一行要快。

    data = [tuple(r) for r in cip_codes.values]
    
    cursor = cnx.cursor()
    
    insert_sql = """InsertCIP(%s, %s, %s, %s)"""
    
    execute_batch(cur, insert_sql, data, page_size=1000 )
    
    cursor.commit()
    
    cursor.close()
    

    希望对您有所帮助,我不确定 InsertCIP 是什么样的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 2017-06-21
      • 2020-11-07
      • 2019-06-23
      相关资源
      最近更新 更多