Untitled
unknown
python
2 years ago
1.3 kB
5
Indexable
import mysql from mysql.connector import connection from sqlalchemy import create_engine, Column, column, text, String, Integer, ForeignKey, select, and_, or_, not_, between, func from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker class Animal: def __init__(self, name, age): self.name = name self.age = age # Tworzenie silnika -> database_url = 'mysql+mysqlconnector://root:haslomaslo123@localhost:3306/animals' eng = create_engine(database_url) # Zadeklarowanie bazy, na ktorej pracujemy base = declarative_base() class Animals(base): __tablename__ = 'animals' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(255), nullable=False) age = Column(Integer, nullable=False) base.metadata.create_all(eng) # Nalezy otworzyc sesje, aby moc wykonywac operacje na danych. # Otwarta sesja musi byc polaczona z silnikiem. Session = sessionmaker(bind=eng) session = Session() animals = [ {'name': 'Frank', 'age': 7}, ] # session.add_all((Animals(**animal) for animal in animals)) # session.commit() # session.close() obj = vars([Animal('Nutka', 3)]) dict_obj = [vars(obj)] session.add_all((Animals(**obj) for o in obj)) session.commit() session.close()
Editor is loading...