使用 psycopg2 执行 SQL 查询

Executing SQL query with psycopg2

我正在尝试使用 psycopg2 将列表传递到 postgres table。我保持 运行 为异常:

  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%、星期三) ;

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

问题可能与您尝试自行打印错误有关。

尝试替换: print('pggggg', error)raise.

首先,您没有使用绑定变量,这是不好的做法,因为这会导致 SQL 注入。你应该做的是:

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

其中 kwargs 是对应于列名称和值的 key/value 对的字典。这是正确的做法。