婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識(shí)庫 > 基于sqlalchemy對(duì)mysql實(shí)現(xiàn)增刪改查操作

基于sqlalchemy對(duì)mysql實(shí)現(xiàn)增刪改查操作

熱門標(biāo)簽:怎么更改高德地圖標(biāo)注 鄭州網(wǎng)絡(luò)外呼系統(tǒng)價(jià)錢 博樂電銷機(jī)器人 機(jī)器人打電銷電話 電話機(jī)器人是電腦呼號(hào)嗎 上海市三維地圖標(biāo)注 南寧外呼系統(tǒng)招商 云南大數(shù)據(jù)外呼系統(tǒng) 400電話到哪辦理優(yōu)惠

需求場(chǎng)景:

老大讓我利用爬蟲爬取的數(shù)據(jù)寫到或更新到mysql數(shù)據(jù)庫中,百度了兩種方法

1 是使用pymysql連接mysql,通過操作原生的sql語句進(jìn)行增刪改查數(shù)據(jù);

2 是使用sqlalchemy連接mysql,通過ORM模型建表并操作數(shù)據(jù)庫,不需要寫原生的sql語句,相對(duì)簡(jiǎn)單些;

以下就是本次使用sqlalchemy的經(jīng)驗(yàn)之談。

實(shí)現(xiàn)流程:連接數(shù)據(jù)庫》通過模型類創(chuàng)建表》建立會(huì)話》執(zhí)行創(chuàng)建表語句》通過會(huì)話進(jìn)行增刪改查

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)

# 實(shí)例化官宣模型 - Base 就是 ORM 模型
Base = declarative_base()


# 創(chuàng)建服務(wù)單表
class ServiceOrder(Base):
  __tablename__ = 'serviceOrderTable'
  id = Column(Integer, primary_key=True, autoincrement=True)
  serviceOrderId = Column(String(32), nullable=False, index=True, comment='服務(wù)單ID')
  serviceDesc = Column(String(268), comment='服務(wù)說明')
  oneLevelName = Column(String(32), comment='C類別')
  twoLevelName = Column(String(32), comment='T子類')
  threeLevelName = Column(String(32), comment='I項(xiàng)目')
  fourLevelName = Column(String(32), comment='S子項(xiàng)')
  transferTimes = Column(String(32), comment='轉(zhuǎn)派次數(shù)')
  overDueStatus = Column(String(32), comment='過期狀態(tài)')
  serviceTimeLimit = Column(String(32), comment='服務(wù)時(shí)限')
  serTimeLimitTypeName = Column(String(16), comment='時(shí)限類型')  
  # 一對(duì)多:
  # serviceWorkOrder = relationship("ServiceWorkOrder", backref="serviceorder")


# 多對(duì)一:多個(gè)服務(wù)工單可以屬于服務(wù)單
class ServiceWorkOrder(Base):
  __tablename__ = 'serviceWorkOrderTable'
  id = Column(Integer, primary_key=True, autoincrement=True)
  serviceWorkOrderId = Column(String(32), nullable=False, index=True, comment='服務(wù)工單ID')
  workOrderName = Column(String(268), comment='工單名稱')
  fromId = Column(String(32), comment='服務(wù)單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)建時(shí)間') 
  # “多”的一方的book表是通過外鍵關(guān)聯(lián)到user表的:
  # serviceOrder_id = Column(Integer, ForeignKey('serviceOrderTable.id'))

# 創(chuàng)建數(shù)據(jù)庫 如果數(shù)據(jù)庫已存在 則不會(huì)創(chuàng)建 會(huì)根據(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判斷目標(biāo)對(duì)象是否存在,返回True或Faults
      it_exists = session.query(
          exists().where(ServiceOrder.serviceOrderId == item['serviceOrderId'] )
        ).scalar()
    except Exception as e:
      self.log.error(e)
      break
    try:
      # 如果不存在,進(jìn)行新增;存在的話就更新現(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ù)庫已存在 則不會(huì)創(chuàng)建 會(huì)根據(jù)庫名直接連接已有的庫
  init_db()
  # 創(chuàng)建session對(duì)象,進(jìn)行增刪改查:
  session = DBSession()
  # 利用session 增 改數(shù)據(jù) 記得提交
  insert_update()  

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • 基于SQLAlchemy實(shí)現(xiàn)操作MySQL并執(zhí)行原生sql語句
  • python數(shù)據(jù)庫操作mysql:pymysql、sqlalchemy常見用法詳解
  • python orm 框架中sqlalchemy用法實(shí)例詳解
  • python使用SQLAlchemy操作MySQL
  • Python SQLAlchemy入門教程(基本用法)
  • python SQLAlchemy的Mapping與Declarative詳解
  • python SQLAlchemy 中的Engine詳解
  • Python流行ORM框架sqlalchemy安裝與使用教程
  • python 獲取sqlite3數(shù)據(jù)庫的表名和表字段名的實(shí)例
  • Python_查看sqlite3表結(jié)構(gòu),查詢語句的示例代碼
  • python使用sqlite3時(shí)游標(biāo)使用方法
  • Python SQLite3簡(jiǎn)介
  • Python使用flask框架操作sqlite3的兩種方式
  • python與sqlite3實(shí)現(xiàn)解密chrome cookie實(shí)例代碼
  • Python SQLite3數(shù)據(jù)庫日期與時(shí)間常見函數(shù)用法分析
  • Python實(shí)現(xiàn)讀取TXT文件數(shù)據(jù)并存進(jìn)內(nèi)置數(shù)據(jù)庫SQLite3的方法
  • Python開發(fā)SQLite3數(shù)據(jù)庫相關(guān)操作詳解【連接,查詢,插入,更新,刪除,關(guān)閉等】
  • Python sqlite3事務(wù)處理方法實(shí)例分析
  • Python簡(jiǎn)單操作sqlite3的方法示例
  • Python3+SQLAlchemy+Sqlite3實(shí)現(xiàn)ORM教程

標(biāo)簽:秦皇島 定西 澳門 恩施 白銀 寧夏 杭州 益陽

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《基于sqlalchemy對(duì)mysql實(shí)現(xiàn)增刪改查操作》,本文關(guān)鍵詞  基于,sqlalchemy,對(duì),mysql,實(shí)現(xiàn),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《基于sqlalchemy對(duì)mysql實(shí)現(xiàn)增刪改查操作》相關(guān)的同類信息!
  • 本頁收集關(guān)于基于sqlalchemy對(duì)mysql實(shí)現(xiàn)增刪改查操作的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    主站蜘蛛池模板: 达日县| 竹溪县| 治多县| 普兰县| 横山县| 绍兴市| 芦溪县| 鄂州市| 正镶白旗| 三河市| 温宿县| 武鸣县| 三江| 全南县| 乌鲁木齐县| 浮梁县| 华阴市| 三河市| 南投市| 木兰县| 秦皇岛市| 罗平县| 仙桃市| 北海市| 进贤县| 沅陵县| 普兰县| 文安县| 资兴市| 深圳市| 吴川市| 绥棱县| 思南县| 双城市| 莲花县| 无锡市| 上思县| 大田县| 昭通市| 仁化县| 资兴市|