Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- baza danych python dodawanie osob
- from sqlalchemy import Column, ForeignKey, Integer, String, create_engine
- from sqlalchemy.orm import relationship, sessionmaker
- from sqlalchemy.ext.declarative import declarative_base
- engine = create_engine("sqlite:///Osoby.db")
- Base = declarative_base()
- from sqlalchemy import Column, Integer, String
- class Osoby(Base):
- __tablename__ = 'osoby'
- id = Column(Integer, primary_key=True)
- imie = Column(String(20), default='')
- nazwisko = Column(String(30), default='')
- adres_id = Column(String(30),ForeignKey('adresyzam.id'))
- adres = relationship('AdresyZam', backref='osoba')
- email = Column(String(20), default='')
- telefon = Column(Integer)
- emails = relationship('Email', backref='osoba')
- # def __repr__(self):
- # return "<Osoby(imie='%s', nazwisko='%s', email='%s', telefon='&i')>" % (self.imie, self.nazwisko, self.email, self.telefon)
- class Email(Base):
- __tablename__ = 'email'
- id = Column(Integer, primary_key=True)
- email = Column(String(100), default='')
- osoba_id = Column(Integer, ForeignKey('osoby.id'))
- class AdresyZam(Base):
- __tablename__ = 'adresyzam'
- id = Column(Integer, primary_key=True)
- ulica = Column(String(100), nullable=False)
- nr_domu = Column(Integer)
- nr_mieszkania = Column(Integer)
- kod = Column(Integer)
- miasta = Column(String(20), default='')
- #class Znajomi(Base):
- # __tablename__ = 'znajomi'
- # tworzymy tabele
- Base.metadata.create_all(engine)
- # tworzymy sesję, która przechowuje obiekty i umożliwia "rozmowę" z bazą
- BDSesja = sessionmaker(bind=engine)
- sesja = BDSesja()
- # dodajemy dwie klasy, jeżeli tabela jest pusta
- if not sesja.query(Osoby).count():
- sesja.add(Osoby(imie ='Franciszek', nazwisko = 'Lolek', adres_id = 1,telefon = '1223'))
- sesja.add(Osoby(imie ='Roman', nazwisko = 'Bolek', adres_id = 3,telefon = '1213'))
- # tworzymy instancję klasy Osoby reprezentującą klasę "1A"
- inst_osoby = sesja.query(Osoby).filter_by(imie='Franciszek').one()
- # Dodawanie danych do tabeli Email
- sesja.add_all([
- Email(id='1', email='franciszek1@gmail.com', osoba_id=inst_osoby.id),
- Email(id='2', email='franciszek2@gmail.com', osoba_id=inst_osoby.id),
- Email(id='3', email='franiu@gmail.com', osoba_id=inst_osoby.id),
- ])
- def czytajdane():
- for email in sesja.query(Email).join(Osoby).all():
- print(email.id, email.email, email.osoba_id)
- print()
- for osoby in sesja.query(Osoby).join(Email).all():
- print(osoby.id, osoby.imie, osoby.nazwisko, osoby.adres_id)
- czytajdane()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement