使用psycopg2执行SQL查询

时间:2018-02-14 15:54:47

标签: python postgresql psycopg2

我试图使用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 / 201,2675,12,0,24698,0.23,58,7074,0.86,60,59.09,-0.06,-0.10%,星期三);

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

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

问题可能与您单独打印错误的尝试有关。

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