最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python orm 框架中sqlalchemy用法實(shí)例詳解

 更新時(shí)間:2020年02月02日 10:54:56   作者:Dawn__Z  
這篇文章主要介紹了python orm 框架中sqlalchemy用法,結(jié)合實(shí)例形式詳細(xì)分析了Python orm 框架基本概念、原理及sqlalchemy相關(guān)使用技巧,需要的朋友可以參考下

本文實(shí)例講述了python orm 框架中sqlalchemy用法。分享給大家供大家參考,具體如下:

一.ORM簡(jiǎn)介

1. ORM(Object-Relational Mapping,對(duì)象關(guān)系映射):作用是在關(guān)系型數(shù)據(jù)庫(kù)和業(yè)務(wù)實(shí)體對(duì)象之間做一個(gè)映射.

2. ORM優(yōu)點(diǎn):

向開(kāi)發(fā)者屏蔽了數(shù)據(jù)庫(kù)的細(xì)節(jié),使開(kāi)發(fā)者無(wú)需與SQL語(yǔ)句打交道,提高了開(kāi)發(fā)效率;

便于數(shù)據(jù)庫(kù)的遷移,由于每種數(shù)據(jù)庫(kù)的SQL語(yǔ)法有差別,基于Sql的數(shù)據(jù)訪(fǎng)問(wèn)層在更換數(shù)據(jù)庫(kù)時(shí)通過(guò)需要花費(fèi)時(shí)間調(diào)試SQL時(shí)間,而ORM提供了獨(dú)立于SQL的接口,ORM的引擎會(huì)處理不同數(shù)據(jù)庫(kù)之間的差異,所以遷移數(shù)據(jù)庫(kù)時(shí)無(wú)需更改代碼.

應(yīng)用緩存優(yōu)化等技術(shù)有時(shí)可以提高數(shù)據(jù)庫(kù)操作的效率.

3. SQLALchemy:是python中最成熟的ORM框架,資源和文檔很豐富,大多數(shù)python web框架對(duì)其有很好的主持,能夠勝任大多數(shù)應(yīng)用場(chǎng)合,SQLALchemy被認(rèn)為是python事實(shí)上的ORM標(biāo)準(zhǔn).

二、代碼

1.建表

"""
Created on 19-10-22
@author: apple
@description:建表
"""
import pymysql
server = '127.0.0.1'
user = 'root'
# dev
password = '123456'
conn = pymysql.connect(server, user, password, database='DataSave') # 獲取連接
cursor = conn.cursor() # 獲取游標(biāo)
# "**ENGINE=InnoDB DEFAULT CHARSET=utf8**"-創(chuàng)建表的過(guò)程中增加這條,中文就不是亂碼
# 創(chuàng)建表
cursor.execute ("""
CREATE TABLE if not exists lamp_result(
  result_id INT NOT NULL auto_increment primary key,
  product_number VARCHAR(100),
  record_time VARCHAR(100),
  lamp_color INT NOT NULL,
  detect_result VARCHAR(100),
  old_pic_path VARCHAR(100),
  result_pic_path VARCHAR(100)
  )
  ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# 查詢(xún)數(shù)據(jù)
cursor.execute('SELECT * FROM lamp_result')
row = cursor.fetchone()
print(row)
# cursor.execute("INSERT INTO user VALUES('%d', '%s','%s','%s','%s')" % ('xiaoming','qwe','ming','@163.com'))
# 提交數(shù)據(jù),才會(huì)寫(xiě)入表格
conn.commit()
# 關(guān)閉游標(biāo)關(guān)閉數(shù)據(jù)庫(kù)
cursor.close()
conn.close()

2. 數(shù)據(jù)存儲(chǔ)

"""
Created on 19-10-22
@author: apple
@requirement:Anaconda 4.3.0 (64-bit) Python3.6
@description:數(shù)據(jù)存儲(chǔ)
"""
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, create_engine
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
# 連接數(shù)據(jù)庫(kù)
# alter table students convert to character set utf8;
conn = "mysql+pymysql://root:password@0.0.0.0:3306/DataSave"
engine = create_engine(conn, encoding='UTF8', echo=False) # echo=True 打印日志
# 創(chuàng)建session對(duì)象
Session = sessionmaker(bind=engine)
session = Session()
# 數(shù)據(jù)庫(kù)表模型ORM
class DataSaveSystem(Base):
  """
  員工自助信息采集系統(tǒng)
  """
  __tablename__ = 'lamp_result' # 定義表名
  # 定義列名
  result_id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
  product_number = Column(String(50), nullable=True)
  record_time = Column(String(50), nullable=False)
  lamp_color = Column(Integer, nullable=False)
  detect_result = Column(String(100), nullable=False)
  old_pic_path = Column(String(100), nullable=False)
  result_pic_path = Column(String(100), nullable=False)
  def __repr__(self):
    """
    引用該類(lèi)別,輸出結(jié)果
    :return:
    """
    return str(self.__dict__)
    # return '<detect_result:{}>'.format(self.detect_result)
# 插入數(shù)據(jù)
def insert_to_db(product_number=None, record_time=None, lamp_color=None,
         detect_result=None, old_pic_path=None, result_pic_path=None):
  '''
  :param product_number: 產(chǎn)品編號(hào)
  :param record_time: 取原圖時(shí)間
  :param lamp_color: 燈的顏色:1 2 3 4
  :param detect_result: 檢測(cè)結(jié)果
  :param old_pic_path: 原圖路徑
  :param result_pic_path: 結(jié)果圖路徑
  :return: 數(shù)據(jù)是否寫(xiě)入成功
  '''
  information_system_instance = DataSaveSystem(
    product_number=product_number,
    record_time=record_time,
    lamp_color=lamp_color,
    detect_result=detect_result,
    old_pic_path=old_pic_path,
    result_pic_path=result_pic_path)
  # session.add_all([
  #   lamp_result(id=2, name="張2", age=19),
  #   lamp_result(id=3, name="張3", age=20)
  # ])
  session.add(information_system_instance)
  try:
    session.commit() # 嘗試提交數(shù)據(jù)庫(kù)事務(wù)
    # print('數(shù)據(jù)庫(kù)數(shù)據(jù)提交成功')
    return {
      "code": 200,
      "status": True,
      "message": "寫(xiě)入數(shù)據(jù)庫(kù)成功",
    }
  except SQLAlchemyError as e:
    session.rollback()
    print(e)
    return {
      "code": 500,
      "status": False,
      "message": str(e)
    }
# url = "mysql+pymysql://root:password@0.0.0.1:3306/DataSave"
# # echo為T(mén)rue時(shí),打印sql,可用于調(diào)試
# engine = create_engine(url, echo=False, encoding='utf-8', pool_size=5)
# sessionClass = sessionmaker(bind=engine)
# # 創(chuàng)建會(huì)話(huà)
# session = sessionClass()
# # 查所有,并排序
# stuList = session.query(DataSaveSystem).order_by(DataSaveSystem.result_id).all()
# print(stuList)
#
stu = DataSaveSystem(product_number='id1',
    record_time='20191022170400',
    lamp_color='1',
    detect_result='ok',
    old_pic_path='picture/',
    result_pic_path='d')
# session.add(stu)
stuList = [DataSaveSystem(product_number='id1',
    record_time='20191022170400',
    lamp_color='1',
    detect_result='ok',
    old_pic_path='picture/',
    result_pic_path='d'),
      DataSaveSystem(product_number='id1',
    record_time='20191022170400',
    lamp_color='1',
    detect_result='ok',
    old_pic_path='picture/',
    result_pic_path='d')]
# session.add_all(stuList)
# session.commit()
# print('數(shù)據(jù)成功')
if __name__ == '__main__':
  result = insert_to_db(stu)
  print(result)

3.數(shù)據(jù)函數(shù)調(diào)用

"""
Created on 19-10-31
@author: apple
@requirement:Anaconda 4.3.0 (64-bit) Python3.6
@description:調(diào)取函數(shù)基類(lèi)
"""
from data_sql.airconditioning_lamp_datasave.datasave import DataSaveSystem
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, create_engine
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
# 連接數(shù)據(jù)庫(kù)
# alter table students convert to character set utf8;
conn = "mysql+pymysql://root:password@0.0.0.1:3306/DataSave"
engine = create_engine(conn, encoding='UTF8', echo=False) # echo=True 打印日志
# 創(chuàng)建session對(duì)象
Session = sessionmaker(bind=engine)
session = Session()
stuList = [DataSaveSystem(product_number='id1',
    record_time='20191022170400',
    lamp_color='1',
    detect_result='ok',
    old_pic_path='picture/',
    result_pic_path='F'),
      DataSaveSystem(product_number='id1',
    record_time='20191022170400',
    lamp_color='1',
    detect_result='ok',
    old_pic_path='picture/',
    result_pic_path='F'),DataSaveSystem(product_number='id1',
    record_time='20191022170400',
    lamp_color='1',
    detect_result='ok',
    old_pic_path='picture/',
    result_pic_path='F'),DataSaveSystem(product_number='id1',
    record_time='20191022170400',
    lamp_color='1',
    detect_result='ok',
    old_pic_path='picture/',
    result_pic_path='F')]
session.add_all(stuList)
session.commit()
print('數(shù)據(jù)成功')
# # 根據(jù)主建查詢(xún)數(shù)據(jù)
# result = session.query(DataSaveSystem).get(3)
# print(result.old_pic_path)
# # 查詢(xún)第一條
# result = session.query(DataSaveSystem).first()
# print(result) #打印對(duì)象屬性
# 查詢(xún)表關(guān)鍵字的數(shù)據(jù)
result = session.query(DataSaveSystem).filter_by(result_pic_path='a/').first()
print(result)
#修改
session.query(DataSaveSystem).filter(DataSaveSystem.result_pic_path=='a/').update({"detect_result":"不合格"})
session.commit()

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Python常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》、《Python數(shù)學(xué)運(yùn)算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門(mén)與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • Cython 三分鐘入門(mén)教程

    Cython 三分鐘入門(mén)教程

    根據(jù)一些我收到的反饋,大家似乎有點(diǎn)混淆——Cython是用來(lái)生成 C 擴(kuò)展到而不是獨(dú)立的程序的。所有的加速都是針對(duì)一個(gè)已經(jīng)存在的 Python 應(yīng)用的一個(gè)函數(shù)進(jìn)行的。
    2009-09-09
  • Python實(shí)現(xiàn)前向和反向自動(dòng)微分的示例代碼

    Python實(shí)現(xiàn)前向和反向自動(dòng)微分的示例代碼

    自動(dòng)微分技術(shù)(稱(chēng)為“automatic differentiation, autodiff”)是介于符號(hào)微分和數(shù)值微分的一種技術(shù),它是在計(jì)算效率和計(jì)算精度之間的一種折衷。本文主要介紹了Python如何實(shí)現(xiàn)前向和反向自動(dòng)微分,需要的可以參考一下
    2022-12-12
  • Python實(shí)現(xiàn)的檢測(cè)web服務(wù)器健康狀況的小程序

    Python實(shí)現(xiàn)的檢測(cè)web服務(wù)器健康狀況的小程序

    這篇文章主要介紹了Python實(shí)現(xiàn)的檢測(cè)web服務(wù)器健康狀況的小程序,本文使用socket庫(kù)來(lái)實(shí)現(xiàn),需要的朋友可以參考下
    2014-09-09
  • python基礎(chǔ)知識(shí)之私有屬性和私有方法

    python基礎(chǔ)知識(shí)之私有屬性和私有方法

    這篇文章主要介紹了python基礎(chǔ)知識(shí)之私有屬性和私有方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • TensorFlow保存TensorBoard圖像操作

    TensorFlow保存TensorBoard圖像操作

    這篇文章主要介紹了TensorFlow保存TensorBoard圖像操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-06-06
  • 深入了解Python?Flask框架之藍(lán)圖

    深入了解Python?Flask框架之藍(lán)圖

    這篇文章主要為大家介紹了Python?Flask框架之藍(lán)圖,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2021-12-12
  • Python 面向?qū)ο缶幊痰娜筇匦灾^承

    Python 面向?qū)ο缶幊痰娜筇匦灾^承

    繼承也是面向?qū)ο缶幊倘筇匦灾?,本篇文章我們就?lái)學(xué)習(xí)Python中繼承的用處、使用場(chǎng)景及用與不用的區(qū)別,感興趣的朋友一起來(lái)閱讀下面文章吧
    2021-09-09
  • Python實(shí)現(xiàn)曲線(xiàn)擬合操作示例【基于numpy,scipy,matplotlib庫(kù)】

    Python實(shí)現(xiàn)曲線(xiàn)擬合操作示例【基于numpy,scipy,matplotlib庫(kù)】

    這篇文章主要介紹了Python實(shí)現(xiàn)曲線(xiàn)擬合操作,結(jié)合實(shí)例形式分析了Python基于numpy,scipy,matplotlib庫(kù)讀取csv數(shù)據(jù)、計(jì)算曲線(xiàn)擬合及圖形繪制相關(guān)操作技巧,需要的朋友可以參考下
    2018-07-07
  • tensorflow 輸出權(quán)重到csv或txt的實(shí)例

    tensorflow 輸出權(quán)重到csv或txt的實(shí)例

    今天小編就為大家分享一篇tensorflow 輸出權(quán)重到csv或txt的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-06-06
  • Python max函數(shù)中key的用法及原理解析

    Python max函數(shù)中key的用法及原理解析

    最近有童鞋向小編求助怎么樣找到字符串中出現(xiàn)字?jǐn)?shù)最多的字符呢,其實(shí)最簡(jiǎn)單的處理方法是使用max函數(shù),max()函數(shù)用于獲得給定的可迭代對(duì)象中的最大值,關(guān)于Python max函數(shù)key用法跟隨小編一起通過(guò)本文學(xué)習(xí)下吧
    2021-06-06

最新評(píng)論

高雄县| 连平县| 隆化县| 镇宁| 亚东县| 竹溪县| 微山县| 中山市| 常德市| 佛冈县| 景德镇市| 大关县| 金塔县| 凤山县| 湟源县| 桓台县| 莎车县| 昌黎县| 噶尔县| 柯坪县| 井冈山市| 涟源市| 宜君县| 珲春市| 梧州市| 区。| 大港区| 固阳县| 麦盖提县| 肥乡县| 澳门| 开封县| 儋州市| 平邑县| 大理市| 西林县| 进贤县| 武威市| 萍乡市| 马龙县| 渭源县|