Search This Blog

Featured Post

Machine Learning, Big Data, AI, Deep Learning

Showing posts with label SQLAlchemy. Show all posts
Showing posts with label SQLAlchemy. Show all posts

Monday, April 23, 2018

24/4/2018 SQLAlchemy


Flow of building connection with database via SQLAlchemy

Create Engine


Step

Key Code

Inspect

Connecting
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite:///:memory:', echo=True)
Map Declare
>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarative_base()
>>> from sqlalchemy import Column, Integer, String
>>> class User(Base):
...     __tablename__ = 'users'
...
...     id = Column(Integer, primary_key=True)
...     name = Column(String)
...     fullname = Column(String)
...     password = Column(String)
...
...     def __repr__(self):
...        return "<User(name='%s', fullname='%s', password='%s')>" % (
...                             self.name, self.fullname, self.password)
>>> User.__table__ 
Table('users', MetaData(bind=None),
  Column('id', Integer(), table=<users>, primary_key=True, nullable=False),
  Column('name', String(), table=<users>),
  Column('fullname', String(), table=<users>),
  Column('password', String(), table=<users>), schema=None)

Tuesday, April 17, 2018

18/4/2018 SQLAlchemy

Engine



To connect a database, use create_engine() from sqlalchemy. The create_engine() function produce an engine object based on a URL. The URLs follow RFC-1738.


>>>engine = create_engine(dialect+driver://username:password@host:port/database)
The above engine creates a Dialect object tailored towards the database and creates a Pool object which establish a DBAPI connection. However, it's first still not yet established until  Engine.connect()  method is called or an operation which is dependent on this method such as Engine.execute() is invoked.

Monday, April 16, 2018

17/04/2018 SQLAlchemy

SQLAlchemy

Consists of two components
  • Core = a fully featured SQL abstraction toolkit, providing a smooth layer of abstraction over a wide variety of DBAPI implementations and behaviors, as well as a SQL Expression Language which allows expression of the SQL language via generative Python expressions
  • ORM = Object Relational Mapper