Home  >  Q&A  >  body text

python - sqlalchemy batch inserted data, data columns are not equal

# 初始化数据库连接:
engine = create_engine("xxxxx")
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
session = DBSession()
# 测试没有问题的数据
rows_ok = [
    {"name":"aaa","otherdata":"exist_col_aaa"},
    {"name":"bbb","otherdata":"exist_col"},
]
# 测试出问题的数据
rows = [
    {"name":"aaa"},
    {"name":"bbb","otherdata":"exist_col"},
]
# User中有name,otherdata字段
session.execute(User.__table__.insert(),rows)
session.commit()
session.close()

If the keys of all dictionaries in the batch insertion data are consistent, the data can be saved

As long as a key is missing from the dictionary in the List, the entire column will be ignored

The real situation has a lot of columns and a lot of missing data. Is there any solution or other methods?

or

rows = [
    {"name":"aaa"},
    {"name":"aaa"},
    {"name":"aaa"},
    {"name":"aaa"},
    {"name":"bbb","otherdata":"exist_col",....},
]

Converted to

rows = [
    {"name":"aaa","otherdata":"",....},
    {"name":"aaa","otherdata":"",....},
    {"name":"aaa","otherdata":"",....},
    {"name":"aaa","otherdata":"",....},
    {"name":"bbb","otherdata":"exist_col",....},
]
伊谢尔伦伊谢尔伦2683 days ago915

reply all(1)I'll reply

  • 習慣沉默

    習慣沉默2017-06-14 10:54:50

      When defining
    1. schema, use nullable=False

    2. Use session.add_all

    reply
    0
  • Cancelreply