# 初始化数据库连接: 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