Ejemplo con SQLAlchemy

Ejemplo: Conexión a la bases de datos Film

films.py

from sqlalchemy import create_engine  
from sqlalchemy import Column, String  
from sqlalchemy import exc
from sqlalchemy.ext.declarative import declarative_base  
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import create_database, database_exists

# url = "postgres://admin:donotusethispassword@aws-us-east-1-portal.19.dblayer.com:15813/compose"

# PyMySQL
# db = create_engine('mysql+pymysql://scott:tiger@localhost/foo')
# db = create_engine('mysql://{0}:{1}@{2}:{3}/{4}'.format(user, pass, host, port, db))

url = 'mysql+pymysql://{0}:{1}@{2}:{3}/{4}'.format('student', 'donotusethispassword', 'localhost', 3306, 'Film')
# url = 'mysql+pymysql://{0}:{1}@{2}:{3}/{4}'.format('student', 'donotusethispassword', 'alumno.mobi', 3306, 'Film')


db = create_engine(url)
if not database_exists(db.url):
    create_database(db.url)

print('Conection to database Film:' + str(database_exists(db.url)))

base = declarative_base()

class Film(base):  
    __tablename__ = 'films'

    title = Column(String(30), primary_key=True)
    director = Column(String(20))
    year = Column(String(4))

Session = sessionmaker(db)  
session = Session()

base.metadata.create_all(db)


try:
    # Create 
    doctor_strange = Film(title="Doctor Strange", director="Scott Derrickson", year="2016")
    king_kong = Film(title="Kong", director="Jordan Vogt-Roberts", year="2017") 
    session.add(doctor_strange)
    session.add(king_kong)
    session.commit()

    # Read
    films = session.query(Film)  
    for film in films:  
        print(film.title)

    # Update
    king_kong.title = "Kong: La Isla Calavera"  
    session.commit()

    # Delete
    session.delete(doctor_strange)  
    session.commit()

    # Get data
    titulo = input('Introduce un título: ')
    direccion = input('Introduce un director: ')
    valor = int (input('Introduce un año: '))

    pelicula = Film (title = titulo, director = direccion, year = valor)
    session.add(pelicula)
    session.commit()

    # Read
    print('Cambios')
    films = session.query(Film)  
    for film in films:  
        print(film.title)
 
except exc.IntegrityError as e:
    print ('Error: Integrity')
    print (e)

except exc.SQLAlchemyError as e:
    print ('Error: Integrity')
    print (e)

session.close()

Crear el fichero films.py con un editor de texto o un IDE:

xed films.py

Ejecutarlo:

python3  films.py

Deja una respuesta