æ¨å¥½ï¼ææ¯ç åé£å¥ï¼æè°¢æ¨é 读æ¬æï¼æ¬æå°ä¸»è¦ä»ç»ä¸æ¬¾åºç¨äºPythonè¯è¨ä¸çORMæ¡æ¶SQLAlchemyãORMçæ¯Object-Relational Mappingï¼ä½ç¨æ¯æå ³ç³»æ°æ®åºç表ç»ææ å°å°å¯¹è±¡ä¸ã
å®è£
æ¬demo使ç¨çæ¯MySQLæ°æ®åºï¼ORMæ¡æ¶æ¯SQLAlchemyæ¡æ¶ãæ以ï¼æ们é¦å éè¦éè¿Pythonçå 管çå·¥å ·å®è£ éè¦çå ã
- å®è£ MySQLæ°æ®åºé©±å¨ æ们éè¦å®è£ PythonçMySQL驱å¨æ¥è¿æ¥MySQLæå¡å¨ï¼MySQLå®æ¹æä¾äºmysql-connector-python驱å¨ï¼ä½æ¯å¨å®è£ çæ¶åéè¦ç»pipå½ä»¤å ä¸åæ° --allow-externalãå®è£ å½ä»¤å¦ä¸ï¼
pip install mysql-connector-python --allow-external mysql-connector-python
å¤å¶
å¦æ该å½ä»¤å®è£ 失败åå¯ä»¥å°è¯ä¸å¦ä¸å½ä»¤ï¼
pip install mysql-connector
å¤å¶
- å®è£ SQLAlchemy å®è£ 好MySQL驱å¨ä¹åï¼æ¥ä¸æ¥å°±æ¯å®è£ SQLAlchemy模åãåæ ·æ¯éè¿pipå½ä»¤å®è£ ã
pip install sqlalchemy
å¤å¶
ç¯å¢
软件 | çæ¬ |
---|---|
Python | 3.6.7 |
mysql-connector-python | 8.0.22 |
SQLAlchemy | 1.3.22 |
使ç¨
MySQL驱å¨åSQLAlchemy模åå®è£ 好ä¹åï¼æ们çåå¤å·¥ä½å°±åå®äºï¼å°±ä¸æ¥å°±æ¯ä½¿ç¨äºSQLAlchemyæ¡æ¶äºã
1. å¾ æµè¯çæ°æ®è¡¨
该èæ¬å建ä¸ä¸ªå为jobçæ°æ®åºï¼ç¶åå¨è¯¥æ°æ®åºä¸å建ä¸ä¸ªå为job_userç表ãæ¥çå表ä¸æå ¥ä¸¤æ¡è´¦å·ä¿¡æ¯ãæ§è¡è¯¥èæ¬å°±åå¤å¥½äºæµè¯æ°æ®ã
CREATE database if NOT EXISTS `job` default character set utf8mb4 collate utf8mb4_unicode_ci;
use `job`;
CREATE TABLE `job_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL COMMENT 'è´¦å·',
`password` varchar(50) NOT NULL COMMENT 'å¯ç ',
PRIMARY KEY (`id`),
UNIQUE KEY `i_username` (`username`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `job_user`(`id`, `username`, `password`) VALUES (1, 'admin', '123');
INSERT INTO `job_user`(`id`, `username`, `password`) VALUES (2, 'zhangsan', '345');
å¤å¶
2. å¯¼å ¥SQLAlchemyï¼å¹¶åå§åDBSession
# 导å
¥ç¸å
³çå
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# å建对象çåºç±»
Base = declarative_base()
# åå§åæ°æ®åºè¿æ¥
engine = create_engine('mysql+mysqlconnector://root:123@localhost:3306/job')
# å建DBSessionç±»å
DBSession = sessionmaker(bind=engine)
# å®ä¹User对象
class User(Base):
# 表çåå
__tablename__ = 'job_user'
# 表çç»æ
id = Column(int(11), primary_key=True)
username = Column(String(20))
password = Column(String(20))
#å°å¯¹è±¡è½¬ædictåå
¸
def to_dict(self):
return {c.name: getattr(self, c.name, None)
for c in self.__table__.columns}
Base.to_dict = to_dict
å¤å¶
å¦ä¸ä»£ç ï¼ä¸»è¦åäºå¦ä¸ä¸ä»¶äºæ ï¼
- å¯¼å ¥SQLAlchemyæ¡æ¶çç¸å ³ç±»ã
- åå§åæ°æ®è¿æ¥ï¼å建DBSessionç±»å
æ°æ®åºç±»å+æ°æ®åºé©±å¨å称://ç¨æ·å:å£ä»¤@æºå¨å°å:端å£å·/æ°æ®åºå
mysql+mysqlconnector://root:123@localhost:3306/job
å¤å¶
å°±æ¯è¯´æ°æ®åºç±»åæ¯mysqlï¼æ°æ®åºé©±å¨çå称æ¯mysqlconnectorï¼è¿æ¥çç¨æ·åæ¯rootï¼è¿æ¥çå¯ç æ¯123ï¼æºå¨å°åæ¯ï¼localhostï¼ç«¯å£å·æ¯ï¼3306ï¼æ°æ®åºå称æ¯jobãè¿ä¸ªè¿æ¥çæ ¼å¼æ¯åºå®çãæ¥çéè¿å¦ä¸è¯å¥æ¥å建DBSessionç±»åï¼
DBSession = sessionmaker(bind=engine)
å¤å¶
- å®ä¹User对象ï¼è¿ä¸ªå¯¹è±¡éçå±æ§ä¸job_user表éçå段ç¸å¯¹åºã
3. æå ¥æ°æ®
æå ¥æ°æ®çæä½å ¶å®å°±æ¯å建ä¸ä¸ªå¾ æå ¥çUser对象ï¼ç¶åå°è¯¥User对象æ¾å ¥sessionï¼ä¼è¯ï¼ä¸è¿è¡æ交ã
#å建session对象
session = DBSession()
# å建æ°User对象
new_user = User(id=3,username='ceshi',password='456')
# æ·»å å°session
session.add(new_user)
# æ交å³ä¿åå°æ°æ®åºï¼
session.commit()
# å
³ésession
session.close()
å¤å¶
4. æ¥è¯¢æ°æ®
æ ¹æ®ä¸»é®è·åè®°å½
æ ¹æ®ä¸»é®æ¥è¯¢å¯ä»¥ç´æ¥è°ç¨getæ¹æ³ï¼
user = session.query(User).get(1)
print(user and user.to_dict())
å¤å¶
å°±å¯ä»¥ç´æ¥å¾å°å¦ä¸ç»æï¼
{'id': 1, 'username': 'admin', 'password': '123'}
å¤å¶
å½ç¶ä¹å¯ä»¥è¿æ ·åï¼
user = session.query(User) \
.filter(User.id == 1) \
.first()
print(user and user.to_dict())
å¤å¶
ä¸é¢getçæ¹æ³æ¯è¾ç®æ´ï¼åªéç¨äºä¸»é®æ¥è¯¢ï¼ä¸é¢filterçæ¹æ³æ¯è¾éç¨ï¼éç¨äºææå段çæ¥è¯¢ãå ¶ä¸first()çæææ¯è¿åæ¥è¯¢ç»æä¸ç第ä¸æ¡ã
#all()æ¹æ³æ¯è¿åææçæ¥è¯¢ç»æ
users = session.query(User) \
.filter(User.id == 1) \
.all()
#one()æ¹æ³æ¯åªè·åä¸æ¡è®°å½ï¼å¦ææ¾ä¸å°è®°å½æè
å¤æ¡é½ä¼æ¥é
user = session.query(User) \
.filter(User.id == 1) \
.one()
å¤å¶
ANDæ¥è¯¢
å¨å®é 项ç®ä¸ï¼æ们æ¥è¯¢æ°æ®é常æ¯å¤æ¡ä»¶æ¥è¯¢ï¼é£ä¹å¤æ¡ä»¶æ¥è¯¢ç代ç 该æä¹åå¢ï¼
user = session.query(User) \
.filter(User.username == 'admin',
User.password > '123') \
.all()
å¤å¶
ä¸é¢ç代ç çææçåäºä¸é¢çSQLè¯å¥;
select * from job_user where username='admin' and password='123'
å¤å¶
è¿åè®°å½æ¡æ° count()
#è¿åè®°å½æ¡æ° count()
count = session \
.query(User) \
.filter(User.id == 3) \
.count()
print(count)
å¤å¶
å°è®°å½æç §æ个å段è¿è¡æåº order_by()
users = session \
.query(User.id, User.username) \
.filter(User.id > 2) \
.order_by(User.id.desc()) \
.all()
å¤å¶
æ¥çè®°å½æ¯å¦åå¨ exist()
from sqlalchemy.sql import exists
is_exist = session \
.query(exists().where(User.id > 10)) \
.scalar()
å¤å¶
ORæ¥è¯¢
#éè¦å¼å
¥or_å½æ°
from sqlalchemy import or_
users = session.query(User) \
.filter(or_(User.id == 1,
User.username =='zhangsan')) \
.all()
å¤å¶
INæ¥è¯¢
users = session.query(User) \
.filter(User.id.in_([1, 3, 5])) \
.all()
å¤å¶
模ç³æ¥è¯¢
# æ¥è¯¢ç¨æ·åå
å«ãzhangãçç¨æ·è´¦å·
books = session.query(User) \
.filter(User.username.contains('zhang')) \
.all()
å¤å¶
5. æ´æ°æ°æ®
æ´æ°æ°æ®çæä½å ¶å®å°±æ¯é¦å æ¥åºå¾ æ´æ°çæ°æ®ï¼ç¶åè°ç¨updateæ¹æ³æ´æ°ææ°æ°æ®ã
session = DBSession()
new_user = session.query(User).filter(User.id == 2).update({"username": "lisi"})
session.commit()
session.close()
å¤å¶
è¿éæ¯å°idçäº2çé£æ¡æ°æ®çç¨æ·åç±zhangsanæ¹ælisiãåæ ·çè¿æ¯å å建session对象ï¼ç¶åæ交session,æåå ³ésessionã
6. å é¤æ°æ®
å é¤æ°æ®ä¸æ´æ°æ°æ®ç±»ä¼¼ãä¹æ¯å æ¥åºå¾ å é¤çæ°æ®ï¼å¦æåå¨åå é¤ï¼è¿æ¯ç©çå é¤ãä¸é¢çè¯å¥æ¯å é¤idçäº3çç¨æ·è´¦å·ã
# å建session对象
session = DBSession()
old_user = session.query(User).get(3)
# å é¤æ件
session.delete(old_user)
# æ交å³ä¿åå°æ°æ®åºï¼
session.commit()
session.close()
å¤å¶
æ»ç»
æ¬æé¦å ä»ç»äºSQLAlchemyæ¡æ¶çå®è£ ï¼æ¥çä»ç»äºå¦ä½éè¿è¯¥æ¡æ¶å¯¹æ°æ®åºè¡¨è¿è¡å¢å æ¹æ¥ï¼éç¹ä»ç»äºå¸¸ç¨æ¥è¯¢ï¼æ¥è¯¢çæ¹æ³ä¼å¤ï¼å ¶ä¸ä½¿ç¨æå¤çæ¹æ³å°±æ¯filteræ¹æ³ï¼æ们çæ¥è¯¢æ¡ä»¶é½æ¯éè¿è¯¥æ¹æ³ä¼ å ¥çãå¸æ对读è æå们ææ帮å©ã