Python从数据库中读取数据并将其重写到另一个表中

时间:2018-03-18 20:30:41

标签: python database postgresql psycopg2

def store_locations(location):
    db= psycopg2.connect(database=DATABASE, user=USER, password=PASSWD, host=HOST, port=PORT)
    cursor = db.cursor()
    insert_query = "INSERT INTO account_locations2(location) VALUES (%s) ON CONFLICT (location) DO UPDATE SET location=EXCLUDED.location"
    cursor.execute(insert_query, (location))
    db.commit()
    cursor.close()
    db.close()
    return


def read_locations():
    db= psycopg2.connect(database=DATABASE, user=USER, password=PASSWD, host=HOST, port=PORT)
    cursor = db.cursor()
    cursor.execute("SELECT * FROM public_accounts")
    rows = cursor.fetchall()
    for row in rows:
        print(row[3])
        store_locations(row[3])
    db.commit()
    cursor.close()
    db.close()

read_locations()

我曾尝试使用Python从我的数据库中读取表的特定列。当我刚刚打印它时,它成功并显示了我想要的内容。但当我试图将它恢复到另一个表时,它给了我一个错误:

IndexError                                Traceback (most recent call last)
<ipython-input-38-7012639773d6> in <module>()
 23     db.close()
 24 
---> 25 read_locations()

<ipython-input-38-7012639773d6> in read_locations()
 18         location=row[3]
 19         print(location)
---> 20         store_locations(location)
 21     db.commit()
 22     cursor.close()

<ipython-input-38-7012639773d6> in store_locations(location)
  3     cursor = db.cursor()
  4     insert_query = "INSERT INTO account_locations2(location) VALUES (%s) ON CONFLICT (location) DO UPDATE SET location=EXCLUDED.location"
----> 5     cursor.execute(insert_query, (location))
  6     db.commit()
  7     cursor.close()

IndexError: string index out of range

1 个答案:

答案 0 :(得分:1)

cursor.execute()中的第二个参数应该是一个元组:

cursor.execute(insert_query, (location,))

the documentation:

  
      
  • 对于位置变量绑定,第二个参数必须始终是一个序列,即使它包含一个变量(请记住Python需要逗号来创建单个元素元组)
  •   

注意但是您可以在单个查询中执行相同操作:

INSERT INTO account_locations2(location) 
SELECT location FROM public_accounts
ON CONFLICT (location) DO NOTHING
-- when there is a conflict on location
-- then this makes no sense:
-- UPDATE SET location = EXCLUDED.location
-- as both are the same