bulk insert

    engine = create_engine("sqlite://", echo=True)
    Base.metadata.create_all(engine)

    session = Session(engine)
    # session = sessionmaker(bind=engine)

    # create catalog
    tshirt, mug, hat, crowbar = (
        Item("SA T-Shirt", 10.99),
        Item("SA Mug", 6.50),
        Item("SA Hat", 8.99),
        Item("MySQL Crowbar", 16.99),
    )
    session.add_all([tshirt, mug, hat, crowbar])
    # 此处不能够使用bulk_save_objects,如果使用的话他会插入两次Item的数据
    #session.bulk_save_objects([tshirt, mug, hat, crowbar])
    session.commit()

    # create an order
    order = Order("john smith")

    # add three OrderItem associations to the Order and save
    order.order_items.append(OrderItem(mug))
    order.order_items.append(OrderItem(crowbar, 10.99))
    order.order_items.append(OrderItem(hat))
    session.add(order)
    session.commit()

    # query the order, print items
    order = session.query(Order).filter_by(customer_name="john smith").one()
    print(
        [
            (order_item.item.description, order_item.price)
            for order_item in order.order_items
        ]
    )

    # print customers who bought 'MySQL Crowbar' on sale
    # q = session.query(Order).join("order_items", "item")
    # q = q.filter(
    #     and_(Item.description == "MySQL Crowbar", Item.price > OrderItem.price)
    # )
    # print customers who bought 'MySQL Crowbar' on sale
    """SELECT "order".order_id AS order_order_id, "order".customer_name AS order_customer_name, "order".order_date AS order_order_date 
FROM "order" JOIN orderitem ON "order".order_id = orderitem.order_id JOIN item ON item.item_id = orderitem.item_id 
WHERE item.description = ? AND item.price > orderitem.price"""
    """SELECT "order".order_id AS order_order_id, "order".customer_name AS order_customer_name, "order".order_date AS order_order_date, item_1.item_id AS item_1_item_id, item_1.description AS item_1_description, item_1.price AS item_1_price, orderitem_1.order_id AS orderitem_1_order_id, orderitem_1.item_id AS orderitem_1_item_id, orderitem_1.price AS orderitem_1_price 
FROM item, orderitem, "order" LEFT OUTER JOIN orderitem AS orderitem_1 ON "order".order_id = orderitem_1.order_id LEFT OUTER JOIN item AS item_1 ON item_1.item_id = orderitem_1.item_id 
WHERE item.description = ? AND item.price > orderitem.price"""
    q = session.query(Order).options(joinedload(Order.order_items))
    q = q.filter(
        and_(Item.description == "MySQL Crowbar", Item.price > OrderItem.price)
    )

    print([order.customer_name for order in q])

你可能感兴趣的:(mysql)