from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import config
SQLALCHEMY_DATABASE_URL = config.DATABASE_URL
engine = create_engine(SQLALCHEMY_DATABASE_URL)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class User(Base):
__tablename__ = 'test_user'
id = Column(Integer, primary_key = True)
name = Column(String, default="")
score = Column(Integer, default=0)
query = User.__table__.select()
print(query)
query = User.__table__.select(whereclause=User.id == 1)
print(query)
query = User.__table__.select().where(User.id == 1)
print(query)
query = User.__table__.insert().values(id = 1, name = 'wxnacy', score = 1)
print(query)
query = User.__table__.insert(values=dict(id = 1, name = 'wxnacy', score = 1))
print(query)
# 将多个插入语句合并为一个,并执行
items = [{"name": "wxnacy"}, {"name": "wen"}]
session.execute(User.__table__.insert(), items)
query = User.__table__.update().where(User.id == 1).values(name = 'wxnacy')
print(query)
query = User.__table__.update(whereclause=User.id == 1, values=dict(name = 'wxnacy'))
print(query)
query = User.__table__.delete()
print(query)
query = User.__table__.delete().where(User.id == 1)
print(query)
query = User.__table__.delete(whereclause=User.id == 1)
print(query)
from sqlalchemy import select
query = select([User])
print(query)
query = select([User.id, User.name])
print(query)
query = select([User.id, User.name], User.id == 1)
print(query)
from sqlalchemy import and_
query = select([User.id, User.name], and_(User.id == 1, User.name == 'wxnacy'))
print(query)
from sqlalchemy import text
query = select([User.id, User.name], text("id = 1 and name = 'wxnacy'"))
print(query)
from sqlalchemy import text
query = select([User.id, User.name], text("id = :id and name = :name")).params(id = 1, name= 'wxnacy')
print(query)
query = select([User.id, User.name]).where(User.id == 1)
print(query)
from sqlalchemy import and_
query = select([User.id, User.name]).where(and_(User.id == 1, User.name == 'wxnacy'))
print(query)
from sqlalchemy import text
query = select([User.id, User.name]).where(text("id = 1 and name = 'wxnacy'"))
print(query)
from sqlalchemy import text
query = select([User.id, User.name]).where(text("id = :id and name = :name")).params(id = 1, name= 'wxnacy')
print(query)
query = select([User.id, User.name]).limit(10)
print(query)
query = select([User.id, User.name]).order_by(User.id)
print(query)
query = select([User.id, User.name]).order_by(User.id.desc())
print(query)
query = select([User.id, User.name]).group_by(User.name)
print(query)
更多用法详见文档