【发布时间】:2020-11-23 20:52:29
【问题描述】:
我正在尝试使用 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()
【问题讨论】:
标签: python django postgresql psycopg2 delimiter