Dynamic Table Creation and ORM mapping in SqlAlchemy

前端 未结 7 1873
忘了有多久
忘了有多久 2020-12-23 19:18

I\'m fairly new to using relational databases, so I prefer using a good ORM to simplify things. I spent time evaluating different Python ORMs and I think SQLAlchemy is what

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-23 19:48

    We are spoiled by SQLAlchemy.
    What follows below is taken directly from the tutorial,
    and is really easy to setup and get working.

    And because it is done so often,
    the documentation moved to full declarative in Aug 2011.

    Setup your environment (I'm using the SQLite in-memory db to test):

    >>> from sqlalchemy import create_engine
    >>> engine = create_engine('sqlite:///:memory:', echo=True)
    >>> from sqlalchemy import Table, Column, Integer, String, MetaData
    >>> metadata = MetaData()
    

    Define your table:

    >>> players_table = Table('players', metadata,
    ...   Column('id', Integer, primary_key=True),
    ...   Column('name', String),
    ...   Column('score', Integer)
    ... )
    >>> metadata.create_all(engine) # create the table
    

    If you have logging turned on, you'll see the SQL that SQLAlchemy creates for you.

    Define your class:

    >>> class Player(object):
    ...     def __init__(self, name, score):
    ...         self.name = name
    ...         self.score = score
    ...
    ...     def __repr__(self):
    ...        return "" % (self.name, self.score)
    

    Map the class to your table:

    >>> from sqlalchemy.orm import mapper
    >>> mapper(Player, players_table) 
    
    

    Create a player:

    >>> a_player = Player('monty', 0)
    >>> a_player.name
    'monty'
    >>> a_player.score
    0
    

    That's it, you now have a your player table.

提交回复
热议问题