python - 使用 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()
解决方案
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
样子。
推荐阅读
- python - “datetime.date”类型的对象在python中没有len()“
- python - 找到对象边缘之间的中心线
- javascript - 在 tsconfig.json 中找不到“redux-logger”错误的类型定义文件
- python - 如何重新安装和恢复损坏的python?
- python - Pygame 窗口在退出时冻结
- python - 如何使用一个命令解压缩所有 .Z 文件
- javascript - 如何将输出分叉/集群进程通过管道传输到主 stdout/stderr
- swift - 使用 AVAssetExportSession 快速导出 MP4
- c# - 如何在文本块上将转换器文化置于多重绑定中
- excel - 满足条件时重置循环excel vba