目录

SqlAlchemy

外键

 

 


SqlAlechemy

SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。

 

Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:

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

创建表(实例方法)

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey

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)),
)   #表结构
engine = create_engine("mysql+pymysql://root:1234@127.0.0.1:3306/mydb?charset=utf8", max_overflow=5)#链接数据库
metadata.create_all(engine)
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey
 5 
 6 metadata = MetaData()
 7 
 8 user = Table('user', metadata,
 9     Column('id', Integer, primary_key=True),
10     Column('name', String(20)),
11 )
12 
13 color = Table('color', metadata,
14     Column('id', Integer, primary_key=True),
15     Column('name', String(20)),
16 )
17 engine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s11", max_overflow=5)
18 
19 conn = engine.connect()
20 
21 # 创建SQL语句,INSERT INTO "user" (id, name) VALUES (:id, :name)
22 conn.execute(user.insert(),{'id':7,'name':'seven'})
23 conn.close()
24 
25 # sql = user.insert().values(id=123, name='wu')
26 # conn.execute(sql)
27 # conn.close()
28 
29 # sql = user.delete().where(user.c.id > 1)
30 
31 # sql = user.update().values(fullname=user.c.name)
32 # sql = user.update().where(user.c.name == 'jack').values(name='ed')
33 
34 # sql = select([user, ])
35 # sql = select([user.c.id, ])
36 # sql = select([user.c.name, color.c.name]).where(user.c.id==color.c.id)
37 # sql = select([user.c.name]).order_by(user.c.name)
38 # sql = select([user]).group_by(user.c.name)
39 
40 # result = conn.execute(sql)
41 # print result.fetchall()
42 # conn.close()
增删改查

 

创建表(类方法)

#!/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,and_,or_

Base = declarative_base()       #生成一个SqlORM的基类
engine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s12",echo=True)


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)

Base.metadata.create_all(engine)     #创建所有表结构

if __name__ == '__main__':
    SessionCls = sessionmaker(bind=engine)  #创建与数据库的会话
    session = SessionCls()  #链接的实例
    # add(添加数据)
    # h2 = Host(hostname='localhost',ip_addr='127.0.0.1')
    # h3 = Host(hostname='ubuntu5',ip_addr='192.168.1.24',port=20000)
    # session.add(h2)
    # session.add(h3)
    # session.add_all([h2,h3])
    # update(修改数据)
    # obj = session.query(Host).filter(Host.hostname=='localhost').first()#查询数据
    # print("++>",obj)
    # obj.hostname = "test server"
    # delete(删除数据)
    # obj = session.query(Host).filter(Host.hostname=='test server').first()
    # session.delete(obj)
    # session.commit()
 1 # ########## 增 ##########
 2 # u = User(id=2, name='sb')
 3 # session.add(u)
 4 # session.add_all([
 5 #     User(id=3, name='sb'),
 6 #     User(id=4, name='sb')
 7 # ])
 8 # session.commit()
 9  
10 # ########## 删除 ##########
11 # session.query(User).filter(User.id > 2).delete()
12 # session.commit()
13  
14 # ########## 修改 ##########
15 # session.query(User).filter(User.id > 2).update({'cluster_id' : 0})
16 # session.commit()
17 # ########## 查 ##########
18 # ret = session.query(User).filter_by(name='sb').first()
19  
20 # ret = session.query(User).filter_by(name='sb').all()
21 # print ret
22  
23 # ret = session.query(User).filter(User.name.in_(['sb','bb'])).all()
24 # print ret
25  
26 # ret = session.query(User.name.label('name_label')).all()
27 # print ret,type(ret)
28  
29 # ret = session.query(User).order_by(User.id).all()
30 # print ret
31  
32 # ret = session.query(User).order_by(User.id)[1:3]
33 # print ret
34 # session.commit()
增删改查

外键——一对多