python - 从pydev导入数据到postgresql

标签 python sql eclipse postgresql pydev

我正在尝试使用 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/

相关文章:

java - 编辑 Excel 文件时,由于 native 代码错误,崩溃发生在 Java 虚拟机之外

java - 当我在 Eclipse 中创建新项目时,为什么 SVN Checkout 不适合我?

python - Flask Assets 仅在一个文件中查找更改

python - 计算我的函数的大 o

SQL查询一对多关系

php - MySQL查询 - 两行之间的差异

java - 自动构建在 Eclipse 中创建的 Web 应用程序的过程

python - 如何使用 python 和 matplotlib 注释行尾?

python - GridSearchCV 初始化

sql - 将具有相同 ID 的多个查询结果展平为单行?