码迷,mamicode.com
首页 > 数据库 > 详细

SQLAlchemy

时间:2020-03-13 20:40:52      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:closed   image   root   type   实现   mysql   信息   target   port   

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
 
技术图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3  
 4 from sqlalchemy import create_engine
 5  
 6  
 7 engine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s11", max_overflow=5)
 8  
 9 engine.execute(
10     "INSERT INTO ts_test (a, b) VALUES (‘2‘, ‘v1‘)"
11 )
12  
13 engine.execute(
14      "INSERT INTO ts_test (a, b) VALUES (%s, %s)",
15     ((555, "v1"),(666, "v1"),)
16 )
17 engine.execute(
18     "INSERT INTO ts_test (a, b) VALUES (%(id)s, %(name)s)",
19     id=999, name="v1"
20 )
21  
22 result = engine.execute(select * from ts_test)
23 result.fetchall()
使用 Engine/ConnectionPooling/Dialect 进行数据库操作,Engine使用ConnectionPooling连接数据库,然后再通过Dialect执行SQL语句。
技术图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 from sqlalchemy import create_engine
 5 
 6 
 7 engine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s11", max_overflow=5)
 8 
 9 
10 # 事务操作
11 with engine.begin() as conn:
12     conn.execute("insert into table (x, y, z) values (1, 2, 3)")
13     conn.execute("my_special_procedure(5)")
14     
15     
16 conn = engine.connect()
17 # 事务操作 
18 with conn.begin():
19        conn.execute("some statement", {x:5, y:10})
事务

 

技术图片
 1 ‘‘‘
 2 使用 Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 进行数据库操作。Engine使用Schema Type创建一个特定的结构对象,之后通过SQL Expression Language将该对象转换成SQL语句,然后通过 ConnectionPooling 连接数据库,再然后通过 Dialect 执行SQL,并获取结果。
 3 ‘‘‘
 4 
 5 
 6 #!/usr/bin/env python
 7 # -*- coding:utf-8 -*-
 8  
 9 from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey
10  
11 metadata = MetaData()
12  
13 user = Table(user, metadata,
14     Column(id, Integer, primary_key=True),
15     Column(name, String(20)),
16 )
17  
18 color = Table(color, metadata,
19     Column(id, Integer, primary_key=True),
20     Column(name, String(20)),
21 )
22 engine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s11", max_overflow=5)
23  
24 metadata.create_all(engine)
25 # metadata.clear()
26 # metadata.remove()
2
技术图片
#!/usr/bin/env python
# -*- coding:utf-8 -*-

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+mysqldb://root:123@127.0.0.1:3306/s11", max_overflow=5)

conn = engine.connect()

# 创建SQL语句,INSERT INTO "user" (id, name) VALUES (:id, :name)
conn.execute(user.insert(),{id:7,name:seven})
conn.close()

# sql = user.insert().values(id=123, name=‘wu‘)
# conn.execute(sql)
# conn.close()

# sql = user.delete().where(user.c.id > 1)

# sql = user.update().values(fullname=user.c.name)
# sql = user.update().where(user.c.name == ‘jack‘).values(name=‘ed‘)

# sql = select([user, ])
# sql = select([user.c.id, ])
# sql = select([user.c.name, color.c.name]).where(user.c.id==color.c.id)
# sql = select([user.c.name]).order_by(user.c.name)
# sql = select([user]).group_by(user.c.name)

# result = conn.execute(sql)
# print result.fetchall()
# conn.close()


更多内容详见:

    http://www.jianshu.com/p/e6bba189fcbd

    http://docs.sqlalchemy.org/en/latest/core/expression_api.html
增删改查

注:SQLAlchemy无法修改表结构,如果需要可以使用SQLAlchemy开发者开源的另外一个软件Alembic来完成。

技术图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3  
 4 from sqlalchemy.ext.declarative import declarative_base
 5 from sqlalchemy import Column, Integer, String
 6 from sqlalchemy.orm import sessionmaker
 7 from sqlalchemy import create_engine
 8  
 9 engine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s11", max_overflow=5)
10  
11 Base = declarative_base()
12  
13  
14 class User(Base):
15     __tablename__ = users
16     id = Column(Integer, primary_key=True)
17     name = Column(String(50))
18  
19 # 寻找Base的所有子类,按照子类的结构在数据库中生成对应的数据表信息
20 # Base.metadata.create_all(engine)
21  
22 Session = sessionmaker(bind=engine)
23 session = Session()
24  
25  
26 # ########## 增 ##########
27 # u = User(id=2, name=‘sb‘)
28 # session.add(u)
29 # session.add_all([
30 #     User(id=3, name=‘sb‘),
31 #     User(id=4, name=‘sb‘)
32 # ])
33 # session.commit()
34  
35 # ########## 删除 ##########
36 # session.query(User).filter(User.id > 2).delete()
37 # session.commit()
38  
39 # ########## 修改 ##########
40 # session.query(User).filter(User.id > 2).update({‘cluster_id‘ : 0})
41 # session.commit()
42 # ########## 查 ##########
43 # ret = session.query(User).filter_by(name=‘sb‘).first()
44  
45 # ret = session.query(User).filter_by(name=‘sb‘).all()
46 # print ret
47  
48 # ret = session.query(User).filter(User.name.in_([‘sb‘,‘bb‘])).all()
49 # print ret
50  
51 # ret = session.query(User.name.label(‘name_label‘)).all()
52 # print ret,type(ret)
53  
54 # ret = session.query(User).order_by(User.id).all()
55 # print ret
56  
57 # ret = session.query(User).order_by(User.id)[1:3]
58 # print ret
59 # session.commit()
使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 所有组件对数据进行操作。根据类创建对象,对象转换成SQL,执行SQL。

 

SQLAlchemy

标签:closed   image   root   type   实现   mysql   信息   target   port   

原文地址:https://www.cnblogs.com/JcrLive/p/12488614.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!