使用如下所示的字典,我正在使用sqlalchemy将记录插入到PostgreSQL数据库中。
{'Date': ('08-Dec-2018', '08-Jan-2019'), 'Volume/Length': ('23.19', '22.70'), 'Length/Width': ('2.13', '5.22'), 'Weight gm': ('1.32', '1.02')}
对于一条记录,我可以执行以下操作
from sqlalchemy import Table, MetaData, Column, Date, String, Numeric
from sqlalchemy import create_engine
db_string = "postgres://postgres:crytpticpassword@localhost:5432/test"
db = create_engine(db_string)
meta = MetaData(db)
with db.connect() as conn:
if not db.dialect.has_table(db, "table1"):
table = Table("table1", meta,
Column('date', Date, primary_key=True),
Column('volume_to_length', Numeric),
Column('length_to_width', Numeric),
Column('weight_gm', Numeric))
table.create()
else:
table = Table("table1", meta)
insert_statement = table.insert().values(
date="08-Dec-2018", volume_to_length=23.19, length_to_width=2.13, weight_gm=1.32)
conn.execute(insert_statement)
# read records
select_statement = table.select()
result_set = conn.execute(select_statement)
for r in result_set:
print(r)
我该如何以编程方式遍历字典并以pythonic方式逐条插入记录?还有一种方法可以插入许多记录吗?