首页 > 解决方案 > 使用 python psycopg2 将 csv 数据插入 postgres 数据库的零长度分隔符错误

问题描述

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

psycopg2.errors.SyntaxError:“”“”处或附近的零长度分隔标识符

(这里的追溯照片)

我知道该错误很可能是由于 '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()

标签: pythondjangopostgresqlpsycopg2delimiter

解决方案


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样子。


推荐阅读