python orm框架sqlalchemy_python orm 框架中sqlalchemy用法实例详解
本文實例講述了python orm 框架中sqlalchemy用法。分享給大家供大家參考,具體如下:
一.ORM簡介
1. ORM(Object-Relational Mapping,對象關系映射):作用是在關系型數據庫和業務實體對象之間做一個映射.
2. ORM優點:
向開發者屏蔽了數據庫的細節,使開發者無需與SQL語句打交道,提高了開發效率;
便于數據庫的遷移,由于每種數據庫的SQL語法有差別,基于Sql的數據訪問層在更換數據庫時通過需要花費時間調試SQL時間,而ORM提供了獨立于SQL的接口,ORM的引擎會處理不同數據庫之間的差異,所以遷移數據庫時無需更改代碼.
應用緩存優化等技術有時可以提高數據庫操作的效率.
3. SQLALchemy:是python中最成熟的ORM框架,資源和文檔很豐富,大多數python web框架對其有很好的主持,能夠勝任大多數應用場合,SQLALchemy被認為是python事實上的ORM標準.
二、代碼
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() # 獲取游標
# "**ENGINE=InnoDB DEFAULT CHARSET=utf8**"-創建表的過程中增加這條,中文就不是亂碼
# 創建表
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
""")
# 查詢數據
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'))
# 提交數據,才會寫入表格
conn.commit()
# 關閉游標關閉數據庫
cursor.close()
conn.close()
2. 數據存儲
"""
Created on 19-10-22
@author: apple
@requirement:Anaconda 4.3.0 (64-bit) Python3.6
@description:數據存儲
"""
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()
# 連接數據庫
# 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 打印日志
# 創建session對象
Session = sessionmaker(bind=engine)
session = Session()
# 數據庫表模型ORM
class DataSaveSystem(Base):
"""
員工自助信息采集系統
"""
__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):
"""
引用該類別,輸出結果
:return:
"""
return str(self.__dict__)
# return ''.format(self.detect_result)
# 插入數據
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: 產品編號
:param record_time: 取原圖時間
:param lamp_color: 燈的顏色:1 2 3 4
:param detect_result: 檢測結果
:param old_pic_path: 原圖路徑
:param result_pic_path: 結果圖路徑
:return: 數據是否寫入成功
'''
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() # 嘗試提交數據庫事務
# print('數據庫數據提交成功')
return {
"code": 200,
"status": True,
"message": "寫入數據庫成功",
}
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為True時,打印sql,可用于調試
# engine = create_engine(url, echo=False, encoding='utf-8', pool_size=5)
# sessionClass = sessionmaker(bind=engine)
# # 創建會話
# 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('數據成功')
if __name__ == '__main__':
result = insert_to_db(stu)
print(result)
3.數據函數調用
"""
Created on 19-10-31
@author: apple
@requirement:Anaconda 4.3.0 (64-bit) Python3.6
@description:調取函數基類
"""
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()
# 連接數據庫
# 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 打印日志
# 創建session對象
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('數據成功')
# # 根據主建查詢數據
# result = session.query(DataSaveSystem).get(3)
# print(result.old_pic_path)
# # 查詢第一條
# result = session.query(DataSaveSystem).first()
# print(result) #打印對象屬性
# 查詢表關鍵字的數據
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()
希望本文所述對大家Python程序設計有所幫助。
總結
以上是生活随笔為你收集整理的python orm框架sqlalchemy_python orm 框架中sqlalchemy用法实例详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 马桶有两个反水弯不拆除可以吗?
- 下一篇: 福利彩票双色球兑奖时间?