Updating entire column with data from tuple in PostgreSQL(psycopg2)

时间:2016-04-21 22:46:47

标签: python-2.7 psycopg2 postgresql-9.3

First of all, there is my script:

import psycopg2
import sys

data = ((160000,),
        (40000,),
        (75000,),
        )

def main():
    try:
        connection = psycopg2.connect("""host='localhost' dbname='postgres'
                                         user='postgres'""")
        cursor = connection.cursor()
        query = "UPDATE Planes SET Price=%s"
        cursor.executemany(query, data)
        connection.commit()

    except psycopg2.Error, e:
        if connection:
            connection.rollback()
        print 'Error:{0}'.format(e)

    finally:
        if connection:
            connection.close()

if __name__ == '__main__':
    main()

This code works of course, but not in the way I want. It updates entire column 'Price' which is good, but it updates it only by use of the last value of 'data'(75000).

(1, 'Airbus', 75000, 'Public')
(2, 'Helicopter', 75000, 'Private')
(3, 'Falcon', 75000, 'Military')

My desire output would look like:

(1, 'Airbus', 160000, 'Public')
(2, 'Helicopter', 40000, 'Private')
(3, 'Falcon', 75000, 'Military')

Now, how can I fix it?

1 个答案:

答案 0 :(得分:0)

如果没有在我的机器上设置数据库进行调试,我无法确定,但看起来查询是个问题。执行时

  

UPDATE Planes SET Price =%s

我认为它正在更新整个列,并从您的数据元组迭代值。相反,您可能需要字典

的元组

response

并将查询更改为

({'name':'Airbus', 'price':160000}, {'name':'Helicopter', 'price':40000}...)

查看this article的最底部,了解类似的表述。要确定这确实是问题,您只需执行一次查询("""UPDATE Planes SET Price=%(price)s WHERE Name=%(name)s"""),我敢打赌您将获得数据元组中第一个值的完整价格列。