python orm 框架中sqlalchemy用法实例详解


Posted in Python onFebruary 02, 2020

本文实例讲述了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 '<detect_result:{}>'.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 相关文章推荐
Python设计模式编程中解释器模式的简单程序示例分享
Mar 02 Python
Python和C/C++交互的几种方法总结
May 11 Python
Python元字符的用法实例解析
Jan 17 Python
python 给DataFrame增加index行名和columns列名的实现方法
Jun 08 Python
opencv python 图像去噪的实现方法
Aug 31 Python
python调用其他文件函数或类的示例
Jul 16 Python
python+opencv3生成一个自定义纯色图教程
Feb 19 Python
Tensorflow tf.nn.depthwise_conv2d如何实现深度卷积的
Apr 20 Python
使用darknet框架的imagenet数据分类预训练操作
Jul 07 Python
Django项目在pycharm新建的步骤方法
Mar 02 Python
Python与C/C++的相互调用案例
Mar 04 Python
Python类方法总结讲解
Jul 26 Python
使用Python操作ArangoDB的方法步骤
Feb 02 #Python
详解有关PyCharm安装库失败的问题的解决方法
Feb 02 #Python
Python 模拟生成动态产生验证码图片的方法
Feb 01 #Python
Python递归及尾递归优化操作实例分析
Feb 01 #Python
Python异步编程之协程任务的调度操作实例分析
Feb 01 #Python
python随机生成大小写字母数字混合密码(仅20行代码)
Feb 01 #Python
Python random模块制作简易的四位数验证码
Feb 01 #Python
You might like
浅谈Windows下 PHP4.0与oracle 8的连接设置
2006/10/09 PHP
php删除文件夹及其文件夹下所有文件的函数代码
2013/01/23 PHP
基于jquery的用鼠标画出可移动的div
2012/09/06 Javascript
中国地区三级联动下拉菜单效果分析
2012/11/15 Javascript
Three.js源码阅读笔记(光照部分)
2012/12/27 Javascript
node.js实现逐行读取文件内容的代码
2014/06/27 Javascript
javascript中slice(),splice(),split(),substring(),substr()使用方法
2015/03/13 Javascript
jquery-tips悬浮提示插件分享
2015/07/31 Javascript
JavaScript中访问id对象 属性的方式访问属性(实例代码)
2016/10/28 Javascript
微信小程序开发之大转盘 仿天猫超市抽奖实例
2016/12/08 Javascript
JavaScript基础心法 深浅拷贝(浅拷贝和深拷贝)
2018/03/05 Javascript
vue 刷新之后 嵌套路由不变 重新渲染页面的方法
2018/09/13 Javascript
vue history 模式打包部署在域名的二级目录的配置指南
2019/07/02 Javascript
JS实现简单tab选项卡切换
2019/10/25 Javascript
vue中keep-alive,include的缓存问题
2019/11/26 Javascript
小谈angular ng deploy的实现
2020/04/07 Javascript
[47:46]完美世界DOTA2联赛 Magma vs GXR 第三场 11.07
2020/11/10 DOTA
python用ConfigObj读写配置文件的实现代码
2013/03/04 Python
python实现zencart产品数据导入到magento(python导入数据)
2014/04/03 Python
Python3中使用urllib的方法详解(header,代理,超时,认证,异常处理)
2016/09/21 Python
Python 实现数据库(SQL)更新脚本的生成方法
2017/07/09 Python
python3+PyQt5+Qt Designer实现堆叠窗口部件
2018/04/20 Python
基于python实现百度翻译功能
2019/05/09 Python
python字符串切割:str.split()与re.split()的对比分析
2019/07/16 Python
在python中创建指定大小的多维数组方式
2019/11/28 Python
Scrapy中如何向Spider传入参数的方法实现
2020/09/28 Python
python爬虫中PhantomJS加载页面的实例方法
2020/11/12 Python
pycharm远程连接服务器并配置python interpreter的方法
2020/12/23 Python
达拉斯牛仔官方商店:Dallas Cowboys Pro Shop
2018/02/10 全球购物
德国游戏机商店:Konsolenkost
2019/12/08 全球购物
C# Debug和Testing相关面试题
2015/10/25 面试题
军校制空专业毕业生自我鉴定
2013/11/16 职场文书
档案检查欢迎词
2014/01/13 职场文书
综合素质自我评价评语
2015/03/06 职场文书
2015年三万活动总结
2015/03/25 职场文书
云服务器部署 Web 项目的实现步骤
2022/06/28 Servers