# 初始化数据库连接:
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()
如果批量插入数据中所有字典的key一致,则数据能保存
只要List中字典缺失一个key,会导致整个列被忽略
真实的情况列数很多,而且缺失数据也很多.有没有解决办法,或者使用其它方法?
或者将
rows = [
{"name":"aaa"},
{"name":"aaa"},
{"name":"aaa"},
{"name":"aaa"},
{"name":"bbb","otherdata":"exist_col",....},
]
转化为
rows = [
{"name":"aaa","otherdata":"",....},
{"name":"aaa","otherdata":"",....},
{"name":"aaa","otherdata":"",....},
{"name":"aaa","otherdata":"",....},
{"name":"bbb","otherdata":"exist_col",....},
]
schema定义的时候, 用
nullable=False
用
session.add_all