标签:
SqlAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简而言之:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。
MySQL-Python : mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname> pymysql : mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>] MySQL-Connector : mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname> cx_Oracle : oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...] 更多内容:http://docs.sqlalchemy.org/en/latest/dialects/index.html 备注: * Python2.7版本使用mysqldb * Python3.5版本使用pymysql * 使用pip或者源码包安装,确保环境可以正常使用。 * 确保远程数据库服务器可以正常使用,并且拥有远程登陆权限 数据库授权: * mysql -uroot -p # 登陆数据库 * create database wang # 创建数据库 * grant all on wang.* to wang@"%" identified by ‘123‘ # 授权数据库 * flush privileges # 更新
#!/usr/bin/env python3 #coding:utf8 from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey # 创建数据库连接 engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) # 获取元数据 metadata = MetaData() # 定义表 user = Table(‘user‘, metadata, Column(‘id‘, Integer, primary_key=True), Column(‘name‘, String(20)), ) color = Table(‘color‘, metadata, Column(‘id‘, Integer, primary_key=True), Column(‘name‘, String(20)), ) # 创建数据表,如果数据表存在,则忽视 metadata.create_all(engine)
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine # 创建数据库 engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) # 生成一个SqlORM 基类 Base = declarative_base() # 定义表结构 class User(Base): # 表名 __tablename__ = ‘users‘ # 定义id,主键唯一, id = Column(Integer, primary_key=True) name = Column(String(50)) # 寻找Base的所有子类,按照子类的结构在数据库中生成对应的数据表信息 Base.metadata.create_all(engine) # 创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例 Session = sessionmaker(bind=engine) session = Session() # 获取session,然后把对象添加到session # 最后提交并关闭。Session对象可视为当前数据库连接。
(2)增加
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) Base = declarative_base() class User(Base): __tablename__ = ‘users‘ id = Column(Integer, primary_key=True) name = Column(String(50)) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() #### 添加 ######## # 定义一个字段 zengjia = User(id=2, name=‘sbliuyao‘) # 添加字段 session.add(zengjia) # 添加多个字段 session.add_all([ User(id=3, name=‘sbyao‘), User(id=4, name=‘liuyao‘) ]) # 提交以上操作,现在只是在内存中增加,回写到数据库,就必须做提交操作 session.commit()
(3)删除
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) Base = declarative_base() class User(Base): __tablename__ = ‘users‘ id = Column(Integer, primary_key=True) name = Column(String(50)) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() ########### 删除 ########## # 删除user表,id大于2的字段 session.query(User).filter(User.id > 2).delete() session.commit()
(4)修改
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) Base = declarative_base() class User(Base): __tablename__ = ‘users‘ id = Column(Integer, primary_key=True) name = Column(String(50)) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() # user表里的id等于2的字段修改为id=6 session.query(User).filter(User.id == 2).update({‘id‘ : 6}) session.commit()
(5)查询
### 查询方式1 #### # 查询User表中字段是name=liuyao的第一条数据 ret = session.query(User).filter_by(name=‘liuyao‘).all() print(ret) # 输出ret,这是个对象的内存地址 for i in ret: print(i.id,i.name) # 输出ret的内容 ### 查询方式2 #### # 查询user表里字段是name=liuyao的第一条数据 ret = session.query(User).filter_by(name=‘liuyao‘).first() print(ret) # 输出的结果为对象的内存地址 print(ret.name) # 输出结果的name字段 print(ret.id) # 输出结果的id字段 ### 查询方式3 ### # 查询user表里字段是name是liuyao或者mayun的信息打印出来 ret = session.query(User).filter(User.name.in_([‘liuyao‘,‘mayun‘])).all() print(ret) for i in ret: print(i.name,i.id) ### 查询方式4 ### # 可以给返回的结果起一个别名,或者叫标签:可有可无 ret = session.query(User.name.label(‘‘)).all() # 这里的关键是label方法,它的意思是把User的name字段改个名字叫name_label, # 其相当于执行了:select users.name as name_label from User print(ret,type(ret)) ### 查询方式5 ### # 查询User表根据id排序 ret = session.query(User).order_by(User.id).all() print(ret) for i in ret: print(i.name) ### 查询方式6 ### # 查询user表里根据id排序输入0到3的字段 ret = session.query(User).order_by(User.id)[0:3] print(ret) for i in ret: print(i.name) ### 查询方式7 ### # 创建Query查询,filter是where条件,最后调用one()返回唯一行,如果调用all()则返回所有行 user = session.query(User).filter(User.id==‘5‘).one() print(type(user)) # 查看user的类型 print(user.name) # 查看对象的name属性
(6)外键关联
#!/usr/bin/env python3 #coding:utf8 # 导入所需模块 from sqlalchemy import create_engine,func from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String,ForeignKey from sqlalchemy.orm import sessionmaker,relationship # 生成sqlorm基类 Base = declarative_base() # 创建数据库连接 engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) # 目的是一个人可以拥有多本书,那么在数据库里的一对多关系 class User(Base): # 表名 __tablename__ = ‘user‘ # id字段 id = Column(String(20), primary_key=True) # 名字字段 name = Column(String(20)) # 一对多: # 内容不是表名而是定义的表结构名字 books = relationship(‘Book‘) class Book(Base): # 表明 __tablename__ = ‘book‘ # id字段 id = Column(String(20), primary_key=True) # 名字字段 name = Column(String(20)) # “多”的一方的book表是通过外键关联到user表的: # ForeignKey是外键 关联user表的id字段 user_id = Column(String(20), ForeignKey(‘user.id‘)) # 创建所需表 Base.metadata.create_all(engine) if __name__ == ‘__main__‘: # 绑定,生成会话 SessionCls = sessionmaker(bind=engine) session = SessionCls() # 创建用户 liuyao = User(id=‘1‘,name=‘liuyao‘) ali = User(id=‘2‘,name=‘ali‘) # 添加字段 session.add_all([liuyao,ali]) # 提交 session.commit() # 创建白鹿原这本书,指定谁是拥有者 Whitedeer = Book(id=‘1‘,name=‘White_deer‘,user_id = ‘1‘) # 创建三体这本书,指定谁是拥有者 Threebody = Book(id=‘2‘,name=‘Three_body‘,user_id = ‘2‘) # 添加字段 session.add_all([Whitedeer,Threebody]) # 提交 session.commit()
#!/usr/bin/env python3 #coding:utf8 from sqlalchemy import Column, Sequence, String, Integer, ForeignKey from sqlalchemy import create_engine # 导入创建连接驱动 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import relationship, backref # 这个url可以用urlparse解析, 其中echo=True表示执行时显示sql语句 engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) # 生成了declarative基类, 以后的model继承此类 Base = declarative_base() class Parent(Base): __tablename__ = ‘parent‘ id = Column(Integer, primary_key=True) name = Column(String(64),unique=True,nullable=False) children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = ‘child‘ id = Column(Integer, primary_key=True) name = Column(String(64),unique=True,nullable=False) parent_id = Column(Integer, ForeignKey(‘parent.id‘)) parent = relationship("Parent", back_populates="children") Base.metadata.create_all(engine) # 创建所有表结构 if __name__ == ‘__main__‘: SessionCls = sessionmaker(bind=engine) # 创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例 session = SessionCls() mama = Parent(id=‘1‘,name=‘mamaxx‘) baba = Parent(id=‘2‘,name=‘babaoo‘) session.add_all([mama,baba]) onesb = Child(id=‘1‘,name=‘onesb‘,parent_id=‘2‘) twosb = Child(id=‘2‘,name=‘twosb‘,parent_id=‘2‘) session.add_all([onesb,twosb]) session.commit()
#!/usr/bin/env python3 #coding:utf8 from sqlalchemy import create_engine,func,Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String,ForeignKey from sqlalchemy.orm import sessionmaker,relationship Base = declarative_base() # 关系表 Host2Group = Table(‘host_2_group‘,Base.metadata, Column(‘host_id‘,ForeignKey(‘hosts.id‘),primary_key=True), Column(‘group_id‘,ForeignKey(‘group.id‘),primary_key=True), ) engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/wang", max_overflow=5) class Host(Base): __tablename__ = ‘hosts‘ id = Column(Integer,primary_key=True,autoincrement=True) hostname = Column(String(64),unique=True,nullable=False) ip_addr = Column(String(128),unique=True,nullable=False) port = Column(Integer,default=22) groups = relationship(‘Group‘, secondary= Host2Group, backref = ‘host_list‘) class Group(Base): __tablename__ = ‘group‘ id = Column(Integer,primary_key=True) name = Column(String(64),unique=True,nullable=False) Base.metadata.create_all(engine) # 创建所有表结构 if __name__ == ‘__main__‘: SessionCls = sessionmaker(bind=engine) session = SessionCls() g1 = Group(name=‘g1‘) g2 = Group(name=‘g2‘) g3 = Group(name=‘g3‘) g4 = Group(name=‘g4‘) session.add_all([g1,g2,g3,g4]) session.commit()
标签:
原文地址:http://www.cnblogs.com/wang-yc/p/5720284.html