【问题标题】:import data from pydev to postgresqll将数据从 pydev 导入到 postgresql
【发布时间】:2017-11-21 17:32:37
【问题描述】:

我正在尝试使用 pgadmin4 将数据从 Eclipse 上的 pydev 移动到 postgresql。为什么我的代码打印“错误 %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()

【问题讨论】:

    标签: python sql eclipse postgresql pydev


    【解决方案1】:

    如果表 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-20
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多