python 操作 mysql

1.pymysql
2.ORM框架SQLAlchemy

一、python原有模块 pymysql

安装
pip install pymysql
使用

import pymysql
conn = pymysql.connect(host='',port = 3306,user ='',passwd='',db='',)
cursor = conn.cursor()
cursor = conn.cursor(cursor=pymysql.cursor.DictCursor)
effect_row = conn.execute('sql','argv')
conn.commit()
newid = conn.lastrowid
row1 = conn.fetchone
row2 = conn.fetchmany(n)
row3 = conn.fetchall()
cursor.scroll(n,'absolute')
cursor.scroll(n,'relative')
cursor.close()
conn.close()

二、ORM框架SQLAlchemy
安装
pip install SQLAlchemy
使用
1.创建engine,使用ConnectionPooling 连接数据库,使用 Dialect执行sql

form sqlalchemy import create_engine
engine = create_engine
('mysql+pymysql://user:pass@host:port/dbname?charset =utf8',max_overflow=5)                      ('mysql+mysqldb://user:password@host:port/dbname')                   ('mysql+mysqlconnector://user:password@host:port/dbname')                 ('oracle+cx_oracle://user:pass@host:port/dbname')
cursor = engine.execute('sql',[(**args),()])
cursor.fetchone
cursor.fetchmany()
cursor.fetchall

2.ORM使用

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index  #(列,整数,字符串,外键,唯一索引,索引)
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine

engine = create_engine('mysql+pymysql://user:pass@host:port/dbname',max_overflow=5)
Base = declarative_base()
#创建表
class table(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(32),default='red', unique=True)
    extra = Column(String(16),index=True, nullable=True,ForeignKey("favor.nid"))


    __table_args__ = (
    UniqueConstraint('id', 'name', name='uix_id_name'),
    Index('uix_id_name', 'name', 'extra'),
    )

def init_db():
    Base.metadata.create_all(engine)


def drop_db():
    Base.metadata.drop_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

#增删改查

session.add(Users(name="alex0", extra='sb'))
session.add_all([
    Users(name="alex1", extra='sb'),
    Users(name="alex2", extra='sb'),
])

session.query(Users).filter(Users.id > 2).delete()


session.query(Users).filter(Users.id > 2).update({"name" : "099"})
session.query(Users).filter(Users.id > 2).update({Users.name: Users.name + "099"}, synchronize_session=False)
session.query(Users).filter(Users.id > 2).update({"num": Users.num + 1}, synchronize_session="evaluate")
session.commit()


ret = session.query(Users).all()
ret = session.query(Users.name, Users.extra).all()
ret = session.query(Users).filter_by(name='alex').all()
ret = session.query(Users).filter_by(name='alex').first()
ret = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name='fred').order_by(User.id).all()
ret = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name='ed').all()


# 条件
ret = session.query(Users).filter_by(name='alex').all()
ret = session.query(Users).filter(Users.id > 1, Users.name == 'eric').all()
ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == 'eric').all()
ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()
ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()
ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='eric'))).all()

from sqlalchemy import and_, or_
ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all()
ret = session.query(Users).filter(or_(Users.id < 2, Users.name == 'eric')).all()
ret = session.query(Users).filter(
    or_(
        Users.id < 2,
        and_(Users.name == 'eric', Users.id > 3),
        Users.extra != ""
    )).all()


# 通配符
ret = session.query(Users).filter(Users.name.like('e%')).all()
ret = session.query(Users).filter(~Users.name.like('e%')).all()

# 限制
ret = session.query(Users)[1:2]

# 排序
ret = session.query(Users).order_by(Users.name.desc()).all()
ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all()

# 分组
from sqlalchemy.sql import func

ret = session.query(Users).group_by(Users.extra).all()
ret = session.query(
    func.max(Users.id),
    func.sum(Users.id),
    func.min(Users.id)).group_by(Users.name).all()

ret = session.query(
    func.max(Users.id),
    func.sum(Users.id),
    func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all()

# 连表

ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all()

ret = session.query(Person).join(Favor).all()

ret = session.query(Person).join(Favor, isouter=True).all()


# 组合
q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union(q2).all()

q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union_all(q2).all()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值