使用 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)
我想将以下字典的结果插入数据库(我使用的是 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)