我正在尝试使用 psycopg2 将列表传递到 postgres 表中。我不断遇到异常:
File "c:/Python27/Projects/Newsletter/newsletter.py", line 148, in <module>
insert_pg(listString)
File "c:\Python27\Projects\Newsletter\pg.py", line 23, in insert_pg
print('pggggg', error)
IOError: [Errno 0] Error
数据非常混乱(请原谅我),但这是代码片段。我从 newsletter.py 运行它:
if __name__ == '__main__':
dataList = [today, str(int(round(float(str(spxprice.replace(',', '')))))), str(int(round(float(spxchg)))), str(int(round(float(spxpchg)))), str(int(round(float(str(dowprice.replace(',', '')))))), dowpchg, str(int(round(float(dowchg)))), str(int(round(float(str(ndxprice.replace(',', '')))))), ndxpchg, str(int(round(float(ndxchg)))), ''.join(oilPrice[4]), ''.join(getOilChg), ''.join(getOilPct), dayName]
listString = ', '.join(dataList)
insert_pg(listString)
这是 pg.py,我从以下位置导入 insert_pg:
import psycopg2
from config import config
import sys
def insert_pg(thedata):
sql = ("""insert into prices values (%s);""" % thedata)
conn = None
try:
# read database configuration
params = config()
# connect to the PostgreSQL database
conn = psycopg2.connect(**params)
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql)
conn.commit()
cur.close()
print 'Success.'
except (Exception, psycopg2.DatabaseError) as error:
print('pggggg', error)
finally:
if conn is not None:
conn.close()
打印时sql的输出:
插入价格值(02/14/2018, 2675, 12, 0, 24698, 0.23, 58, 7074, 0.86, 60, 59.09, -0.06, -0.10%, 星期三);
不知道我在这里哪里出错了。数据库连接正常。有任何想法吗?