1. 程式人生 > >limit和offset、切片操作

limit和offset、切片操作

list UNC query 意思 Coding ssi func fir gin

技術分享圖片

#encoding: utf-8

from sqlalchemy import create_engine,Column,Integer,String,Float,func,and_,or_,    DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from random import randint
from datetime import datetime

HOSTNAME = 127.0.0.1

PORT = 3306

DATABASE 
= first_sqlalchemy USERNAME = root PASSWORD = 123456 #dialect+driver://username:password@host:port/database DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) engine = create_engine(DB_URI) Base
= declarative_base(engine) # Session = sessionmaker(engine) # session = Session() session = sessionmaker(engine)() #Session(**local_kw) class Article(Base): __tablename__ = article id = Column(Integer,primary_key=True,autoincrement=True) title = Column(String(50),nullable=False) create_time
= Column(DateTime,default=datetime.now) def __repr__(self): return <article:{title}>.format(title=self.title) # Base.metadata.drop_all() # # Base.metadata.create_all() # # # for x in range(0,100): # article = Article(title = ‘title%s‘%x) # session.add(article) # session.commit() #第一limit的用法,限制查詢多少數據 article = session.query(Article).limit(10).all()#用limit限制只查詢10個數據 print(article) #第二個參數offset的用法,本意是偏移量,在這裏就是從多少開始查詢 article_offset = session.query(Article).offset(10).all() print(article_offset) #offset和limit聯合起來用,就相當於python 的字符串和列表、元祖的切片操作 article_offset_limit = session.query(Article).offset(10).limit(5).all() print(article_offset_limit) #如果查詢最新的10篇文章,就可以用order_by 和 limit 一起用 article_order_by_limit = session.query(Article).order_by(Article.id.desc()).limit(10).all() print(article_order_by_limit) #slice,本身就是切片的意思 article_order_by_slice = session.query(Article).order_by(Article.id.desc()).slice(0,10).all() print(article_order_by_slice) #還有一個更簡單的方法,就想python的列表切片操作 article_list_slice = session.query(Article).order_by(Article.id.desc())[0:10] print(article_list_slice)

limit和offset、切片操作