Python从数据库中读取数据并将其重写到另一个表中
我曾尝试使用Python从数据库中读取表的特定列。当我刚刚打印它时,它成功地显示了我想要的内容。但当我试图将其还原到另一个表时,它给了我一个错误:Python从数据库中读取数据并将其重写到另一个表中,python,database,postgresql,psycopg2,Python,Database,Postgresql,Psycopg2,我曾尝试使用Python从数据库中读取表的特定列。当我刚刚打印它时,它成功地显示了我想要的内容。但当我试图将其还原到另一个表时,它给了我一个错误: def store_locations(location): db= psycopg2.connect(database=DATABASE, user=USER, password=PASSWD, host=HOST, port=PORT) cursor = db.cursor() insert_query = "INSERT
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()
索引器错误回溯(最近一次调用)
在()
23分贝关闭()
24
--->25读单元位置()
在read_位置()中
18位置=第[3]行
19打印(位置)
--->20个门店位置(位置)
21 db.commit()
22.关闭()
店内位置(位置)
3 cursor=db.cursor()
4 insert\u query=“插入帐户位置2(位置)冲突时的值(%s)(位置)DO UPDATE SET location=已排除。位置”
---->5游标执行(插入查询(位置))
6db.commit()
7.关闭()
索引器错误:字符串索引超出范围
游标.execute()中的第二个参数应为元组:
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
- 对于位置变量绑定,第二个参数必须始终是序列,即使它包含单个变量(请记住,Python需要逗号来创建单个元素元组)
插入账户位置2(位置)
从公共帐户中选择位置
关于冲突(位置)什么也不做
--当发生位置冲突时
--那么这就没有意义了:
--更新集位置=排除。位置
--因为两者都是一样的
(位置)
->(位置,)
您如何调用方法以及向方法传递什么?您的方法不返回任何内容。另外,为什么不使用插入到。。。选择代码>一个查询?
cursor.execute(insert_query, (location,))