基于sqlalchemy對mysql實現(xiàn)增刪改查操作
需求場景:
老大讓我利用爬蟲爬取的數(shù)據(jù)寫到或更新到mysql數(shù)據(jù)庫中,百度了兩種方法
1 是使用pymysql連接mysql,通過操作原生的sql語句進行增刪改查數(shù)據(jù);
2 是使用sqlalchemy連接mysql,通過ORM模型建表并操作數(shù)據(jù)庫,不需要寫原生的sql語句,相對簡單些;
以下就是本次使用sqlalchemy的經(jīng)驗之談。
實現(xiàn)流程:連接數(shù)據(jù)庫》通過模型類創(chuàng)建表》建立會話》執(zhí)行創(chuàng)建表語句》通過會話進行增刪改查
from sqlalchemy import exists, Column, Integer, String, ForeignKey, exists
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# 創(chuàng)建的數(shù)據(jù)庫引擎
engine = create_engine("mysql+pymysql://user:pwd@ip/數(shù)據(jù)庫名?charset=utf8")
#創(chuàng)建session類型
DBSession = sessionmaker(bind=engine)
# 實例化官宣模型 - Base 就是 ORM 模型
Base = declarative_base()
# 創(chuàng)建服務單表
class ServiceOrder(Base):
__tablename__ = 'serviceOrderTable'
id = Column(Integer, primary_key=True, autoincrement=True)
serviceOrderId = Column(String(32), nullable=False, index=True, comment='服務單ID')
serviceDesc = Column(String(268), comment='服務說明')
oneLevelName = Column(String(32), comment='C類別')
twoLevelName = Column(String(32), comment='T子類')
threeLevelName = Column(String(32), comment='I項目')
fourLevelName = Column(String(32), comment='S子項')
transferTimes = Column(String(32), comment='轉派次數(shù)')
overDueStatus = Column(String(32), comment='過期狀態(tài)')
serviceTimeLimit = Column(String(32), comment='服務時限')
serTimeLimitTypeName = Column(String(16), comment='時限類型')
# 一對多:
# serviceWorkOrder = relationship("ServiceWorkOrder", backref="serviceorder")
# 多對一:多個服務工單可以屬于服務單
class ServiceWorkOrder(Base):
__tablename__ = 'serviceWorkOrderTable'
id = Column(Integer, primary_key=True, autoincrement=True)
serviceWorkOrderId = Column(String(32), nullable=False, index=True, comment='服務工單ID')
workOrderName = Column(String(268), comment='工單名稱')
fromId = Column(String(32), comment='服務單ID')
createUserSectionName = Column(String(32), comment='創(chuàng)建人室')
createUserName = Column(String(32), comment='創(chuàng)建人')
handlerName = Column(String(32), comment='處理人')
statusName = Column(String(32), comment='工單狀態(tài)')
createTime = Column(String(32), comment='創(chuàng)建時間')
# “多”的一方的book表是通過外鍵關聯(lián)到user表的:
# serviceOrder_id = Column(Integer, ForeignKey('serviceOrderTable.id'))
# 創(chuàng)建數(shù)據(jù)庫 如果數(shù)據(jù)庫已存在 則不會創(chuàng)建 會根據(jù)庫名直接連接已有的庫
def init_db():
Base.metadata.create_all(engine)
def drop_db():
Base.metadata.drop_all(engine)
def insert_update():
# all_needed_data_lists 是需要插入數(shù)據(jù)庫的數(shù)據(jù) 格式[{key: value, ... }, { }, { }...]
for item in all_needed_data_lists:
ServiceOrderRow = ServiceOrder(serviceOrderId=item['serviceOrderId'],
serviceDesc=item['serviceDesc'],
oneLevelName=item['oneLevelName'],
twoLevelName=item['twoLevelName'],
threeLevelName=item['threeLevelName'],
fourLevelName=item['fourLevelName'],
transferTimes=item['transferTimes'],
overDueStatus=item['overDueStatus'],
serviceTimeLimit=item['serviceTimeLimit'],
serTimeLimitTypeName=item['serTimeLimitTypeName'],
)
try:
# 利用exists判斷目標對象是否存在,返回True或Faults
it_exists = session.query(
exists().where(ServiceOrder.serviceOrderId == item['serviceOrderId'] )
).scalar()
except Exception as e:
self.log.error(e)
break
try:
# 如果不存在,進行新增;存在的話就更新現(xiàn)存的數(shù)據(jù)
if not it_exists:
session.add(ServiceOrderRow)
else:
session.query(ServiceOrder).filter(ServiceOrder.serviceOrderId == item['serviceOrderId'])\
.update(item)
except Exception as e:
self.log.error(e)
break
try:
session.commit()
self.log.info('數(shù)據(jù)更新成功!')
except:
session.rollback()
self.log.info('數(shù)據(jù)更新失?。?)
if __name__ == "__main__":
# 創(chuàng)建數(shù)據(jù)庫 如果數(shù)據(jù)庫已存在 則不會創(chuàng)建 會根據(jù)庫名直接連接已有的庫
init_db()
# 創(chuàng)建session對象,進行增刪改查:
session = DBSession()
# 利用session 增 改數(shù)據(jù) 記得提交
insert_update()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
MySQL數(shù)據(jù)庫統(tǒng)計函數(shù)COUNT的使用及說明
這篇文章主要介紹了MySQL數(shù)據(jù)庫統(tǒng)計函數(shù)COUNT的使用及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
Mysql報Table?'mysql.user'?doesn't?exist問題的解
這篇文章主要給大家介紹了關于Mysql報Table?'mysql.user'?doesn't?exist問題的解決方法,初學者可能會遇到這個問題,文中通過圖文將解決方法介紹的非常詳細,需要的朋友可以參考下2022-05-05
MySQL跨服務器數(shù)據(jù)映射的實現(xiàn)
本文主要介紹了MySQL跨服務器數(shù)據(jù)映射的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-03-03
mysql一條sql查出多個條件不同的sum或count問題
這篇文章主要介紹了mysql一條sql查出多個條件不同的sum或count問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05

