![](/img/trans.png)
[英]Parsing command line output and storing result in a dictionary using Python
[英]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.