Python学习笔记:SQLAlchemy

Python学习笔记:SQLAlchemy

图片引用自网络,侵删~

  我不知道风   是在哪一个方向吹————   我是在梦中,   她的温存,我的迷醉。

《我不知道风是在哪一个方向吹》,徐志摩

# SQLAlchemy

# SQLAlchemy简介

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

# SQLAlchemy的使用

# 安装相关库

pip install sqlalchemy pip install pymysql

# 导入相关库

from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker

# 关键步骤

engine = create_engine("mysql+pymysql://dev:[email protected]:3306/test")
Base = declarative_base()

class Ticket(Base):
    __tablename__ = 'tickets'
    
    id = Column(Integer, primary_key=True)
    name = Column(String(3))
    number = Column(String(36))
    
    def __repr__(self):
        return "<Ticket(name='%s', number='%s')>" % (self.name, self.number)
        
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
test_ticket = Ticket(name=str(x), number=str(uuid.uuid3(uuid.NAMESPACE_DNS, str(x))))
session.add(test_ticket) 
session.commit()

# Demo

参见github:https://github.com/gaodyun/PythonDemo/tree/master/0002

Demo使用SQLAlchemy实现了数据添加的功能。

# 相关拓展

# PyMySQL

https://pymysql.readthedocs.io/en/latest/user/examples.html https://github.com/PyMySQL/PyMySQL

# SQLAlchemy Migrate

http://sqlalchemy-migrate.readthedocs.io/en/latest/versioning.html https://github.com/openstack/sqlalchemy-migrate

# SQLAlchemy-Wrapper

http://sqlawrapper.lucuma.co https://github.com/jpscaletti/sqlalchemy-wrapper

参考资料: