将数据从pydev导入postgresq

2024-10-03 11:12:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用pgadmin4将eclipse上的pydev数据移动到postgresql。为什么我的代码打印为“错误%s%e”?在postgres中,创建了test123表,但没有上传数据。非常感谢

#!/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()

Tags: csv数据importnewexecutedatasyspostgres
1条回答
网友
1楼 · 发布于 2024-10-03 11:12:18

如果表testtest123已经存在,postgres将不会再次创建它。
不要在一个try/except块中包装多个语句-这会使您很难确定是否识别错误

出于调试目的,您可以执行以下操作:

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()

相关问题 更多 >