繁体   English   中英

使用Python将字典结果存储到数据库(PostgreSQL)

[英]storing the result of a dictionary to the database using Python (PostgreSQL)

我想将以下字典的结果插入数据库(我正在使用PostgreSQL):

companies_list = dict(zip(code, short_name))

运行代码并打印后,此字典的结果将显示以下内容(例如):

companies_list = { '00001': 'A', '00002': 'B', '0010': 'Z'}

所以当我试图将上面的字典插入下面的数据库(代码)时:

con = None
con = psycopg2.connect("dbname = 'testdb' user='user'")
cur = con.cursor()

cur.execute("CREATE TABLE companies_info(code TEXT PRIMARY KEY, short_name TEXT)")


query = "INSERT INTO companies_info ( code, short_name) VALUES ( %(code)s, %(short_name)s)"
cur.executemany(query, companies_list)

con.commit()
con.close()

我得到以下内容:

cur.executemany(query, companies_list)
TypeError: string indices must be integers, not str

任何人都可以解决他的错误?

code = ['00001', '00002', '0010']
short_name = ['A', 'B', 'Z']
companies_list = [tuple((t,)) for t in zip(code, short_name)]
query = "insert into companies_info (code, short_name) values %s"
cursor.executemany(query, companies_list)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM