我正在尝试使用pydev从python发送数据到postgresql。我发现了多个错误,可能真的需要帮助。非常感谢!其中一个错误说:
psycopg2.InterfaceError:游标已经关闭。
任何帮助将不胜感激!
这是我创建表格的代码
#!/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=",")
firstline = 1
con = None
con = psycopg2.connect("host='localhost' dbname='football' user='postgres' password='XXX'")
cur = con.cursor()
con.commit()
cur.execute("DROP TABLE testtest1234")
cur.execute("CREATE TABLE testtest1234 (HY INTEGER)")
for row in readCSV:
if firstline:
firstline=0
continue
new_data = row[19]
try:
cur.execute("INSERT INTO testtest1234 values ("+new_data+")")
cur.execute("SELECT * FROM testtest1234;")
except psycopg2.DatabaseError as e:
if con:
con.rollback()
print ("Error %s % e", e)
sys.exit(1)
finally:
if con:
con.close()
print (new_data)
print(" ".join(row))
out=open("new_data.csv", "w")
output = csv.writer(out)
for row in new_data:
output.writerow(row)
out.close()
这是我在表格中插入的代码
#!/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=",")
con = None
con = psycopg2.connect("host='localhost' dbname='football' user='postgres' password='XXX'")
cur = con.cursor()
con.commit()
for row in readCSV:
new_data = row[19]
print (new_data)
try:
cur.execute("INSERT INTO testtest1234 values ("+new_data+")")
except psycopg2.DatabaseError as e:
if con:
con.rollback()
print ("Error %s % e", 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()
答案 0 :(得分:0)
您正在关闭循环内部的连接,因此只插入第一行。
for row in readCSV:
try:
...
except psycopg2.DatabaseError as e:
...
finally:
if con:
con.close()