执行SQL查询时使用的是holCopg2

2022-04-14 00:00:00 python postgresql psycopg2

问题描述

我正在尝试使用心理拷贝2将一个列表传递到postgres表中。我一直遇到一个异常:

  File "c:/Python27/Projects/Newsletter/newsletter.py", line 148, in <module>
insert_pg(listString)
  File "c:Python27ProjectsNewsletterpg.py", line 23, in insert_pg
    print('pggggg', error)
IOError: [Errno 0] Error

数据非常杂乱(请原谅),但这里有一小段代码。我正在从Newletter.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的输出:

插入价格值(2018年02/14,2675,12,0,24698,0.23,58,7074,0.86,60,59.09,-0.06,-0.10%,星期三);

不确定我在哪里做错了。数据库连接正常。有什么想法吗?

SQL

首先,您没有使用绑定变量,这是一种糟糕的做法,因为这可能导致推荐答案注入。您应该做的是:

cur.execute('INSERT INTO PRICES(col1, col2, ...) VALUES(%(val1)s, %(val2)s, ...)', kwargs)

其中kwargs是与列名和值对应的键/值对的字典。这才是正确的做法。

相关文章