我正在尝试使用 pgadmin4 将数据从 eclipse 上的 pydev 移动到 postgresql。为什么我的代码打印“Error %s % e”?在 postgres 中,正在创建 testtest123 表,但数据未上传到那里。非常感谢!
#!/usr/bin/python
# -*- coding: utf-8 -*-
import psycopg2
import sys
import csv
from itertools import count
path = r'C:\Users\sammy\Downloads\E0.csv'
with open(path, "r") as csvfile:
readCSV = csv.reader(csvfile, delimiter=",")
for row in readCSV:
new_data = [ row[19]]
print (new_data)
con = None
try:
con = psycopg2.connect("host='localhost' dbname='football' user='postgres' password='XXX'")
cur = con.cursor()
cur.execute("CREATE TABLE testtest123 (HY INTEGER PRIMARY KEY)")
cur.execute("INSERT INTO testtest123(new_data)")
cur.execute("SELECT * FROM testtest123;")
con.commit()
except psycopg2.DatabaseError as e:
if con:
con.rollback()
print ("Error %s % e")
sys.exit(1)
finally:
if con:
con.close()
print(" ".join(row))
out=open("new_data.csv", "w")
output = csv.writer(out)
for row in new_data:
output.writerow(row)
out.close()
最佳答案
如果表 testtest123
已经存在,postgres 不会再次创建它。
不要将多个语句包装在一个 try/except
block 中 - 这会使您难以确定错误。
出于调试目的,您可以这样做:
import traceback
# ... your code ...
con = psycopg2.connect("host='localhost' dbname='football' user='postgres' password='XXX'")
cur = con.cursor()
try:
cur.execute("CREATE TABLE testtest123 (HY INTEGER PRIMARY KEY)")
cur.execute("INSERT INTO testtest123(new_data)")
cur.execute("SELECT * FROM testtest123;")
con.commit()
except:
print ("Error:")
traceback.print_exc()
con.rollback()
sys.exit(1)
finally:
if con:
con.close()
关于python - 从pydev导入数据到postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47419211/