当前位置: 首页 > news >正文

SQLAlchemy使用笔记(一)

简介:SQLAlchemy 是 Python 中最流行的 ORM(对象关系映射)工具之一,它允许开发者通过操作Python 类和对象实现对数据库的增删改查,无需直接编写 SQL,同时也保留了底层 SQL 的灵活性。

文章目录

  • 一、连接数据库
  • 二、创建数据表
    • 2.1、使用 MetaData
    • 2.2、使用declarative_base
  • 三、插入数据
    • 3.1、Core方式
    • 3.2、ORM 方式

一、连接数据库

使用 SQLAlchemy 连接数据库主要通过 create_engine() 函数创建引擎(Engine),再通过引擎建立与数据库的连接。

def test_mysql_connection(username, password, host, port, database):"""测试MySQL数据库连接是否成功"""try:# 构建MySQL连接字符串connection_string = f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}"# 创建引擎,设置连接超时engine = create_engine(connection_string,connect_args={"connect_timeout": 10}  # 10秒连接超时)# 尝试连接并获取数据库版本信息with engine.connect() as conn:result = conn.execute(text("SELECT VERSION()"))db_version = result.scalar()return (True, f"MySQL连接成功!数据库版本: {db_version}")except Exception as e:return (False, f"连接失败: {str(e)}")
config = {"username": "root",  # 替换为你的MySQL用户名"password": "qwe123",  # 替换为你的MySQL密码"host": "localhost",  # 数据库主机"port": 3306,  # MySQL默认端口"database": "mydb"  # 数据库名}
success, message = test_mysql_connection(**config)  #使用 ** 语法将配置字典转为关键字参数

二、创建数据表

2.1、使用 MetaData

  • 使用SQLAlchemy 核心功能(MetaData)创建表的实例,这种方式不依赖 ORM模型,直接通过Table和Column定义表。
# 初始化元数据对象
metadata = MetaData()# 定义表结构
orders = Table('orders',  # 表名metadata, #参数 metadata 表示将这个表关联到前面创建的元数据对象# 字段定义Column('id', Integer, primary_key=True, autoincrement=True, comment='订单ID'),Column('user_id', Integer, nullable=False, comment='用户ID'),Column('total_amount', Float, nullable=False, comment='订单总金额'),Column('payment_method', String(30), comment='支付方式'),Column('shipping_address', String(200), comment='收货地址')
)
# 创建所有与metadata关联的表
metadata.create_all(engine)

2.2、使用declarative_base

  • 使用declarative_base 实现Python 类继承的方式定义数据库表,将类属性映射为表字段,类本身映射为数据库表。
# 创建基类
Base = declarative_base()# 定义数据模型
class Product(Base):# 表名__tablename__ = 'products'# 字段定义id = Column(Integer, primary_key=True, autoincrement=True, comment='商品ID')name = Column(String(100), nullable=False, comment='商品名称')price = Column(Float, nullable=False, comment='商品价格')created_at = Column(DateTime, default=datetime.now, comment='创建时间')description = Column(String(500), comment='商品描述')# 根据模型创建所有表
Base.metadata.create_all(engine)

三、插入数据

3.1、Core方式

  • 要向使用 SQLAlchemy 定义的表中插入数据,可以使用insert()方法构建插入语句,然后通过引擎执行。
# 插入单条数据
def insert_single_order():# 构建插入语句insert_stmt = insert(orders).values(user_id=1001,total_amount=299.99,payment_method='credit_card',shipping_address='北京市朝阳区XX街道XX号')# 执行插入with engine.connect() as conn:result = conn.execute(insert_stmt)conn.commit()  # 提交事务print(f"插入成功,新记录ID: {result.inserted_primary_key[0]}")# 插入多条数据
def insert_multiple_orders():# 构建批量插入语句insert_stmt = insert(orders).values([{'user_id': 1002,'total_amount': 159.50,'payment_method': 'alipay','shipping_address': '上海市浦东新区XX路XX号'},{'user_id': 1003,'total_amount': 450.00,'payment_method': 'wechat','shipping_address': '广州市天河区XX街XX号'}])# 执行插入with engine.connect() as conn:result = conn.execute(insert_stmt)conn.commit()  # 提交事务print(f"成功插入 {result.rowcount} 条记录")

3.2、ORM 方式

# 创建会话实例
session = Session()# 创建单个商品实例
product1 = Product(name="笔记本电脑",price=5999.99,description="高性能游戏本"
)
# 批量创建商品实例
products = [Product(name="平板电脑", price=2999.00, description="轻薄便携"),Product(name="无线耳机", price=899.00, description="降噪效果好")
]# 添加单个对象
session.add(product1)
# 批量添加多个对象
session.add_all(products)# 提交事务,完成数据插入
session.commit()

文章转载自:

http://JjS4BTCN.bfcrp.cn
http://CrC1YvVw.bfcrp.cn
http://Yoa8amsL.bfcrp.cn
http://2ep9RvlY.bfcrp.cn
http://sELsvF2Z.bfcrp.cn
http://6C53LLpm.bfcrp.cn
http://DLNMMwDw.bfcrp.cn
http://AuoZS5rh.bfcrp.cn
http://HCcfLTLK.bfcrp.cn
http://V43tdTAI.bfcrp.cn
http://TITYmLor.bfcrp.cn
http://WtXaENYy.bfcrp.cn
http://rmmC5xTJ.bfcrp.cn
http://UnRX6BkG.bfcrp.cn
http://axcAJUNj.bfcrp.cn
http://0TK1Qpqq.bfcrp.cn
http://AIjEXdj9.bfcrp.cn
http://iJb08Tvu.bfcrp.cn
http://NC14z2yW.bfcrp.cn
http://c62RjKIr.bfcrp.cn
http://klfy1Ifq.bfcrp.cn
http://7nKF3zxD.bfcrp.cn
http://Mx7GcAdT.bfcrp.cn
http://vyn2v2tu.bfcrp.cn
http://PRlEP6q6.bfcrp.cn
http://UYPGj7DT.bfcrp.cn
http://axOxsv4y.bfcrp.cn
http://dUWMPpjR.bfcrp.cn
http://HrQGEL0j.bfcrp.cn
http://WzguZgqv.bfcrp.cn
http://www.dtcms.com/a/384565.html

相关文章:

  • 【C#】.net core 8.0 MVC在一次偶然间发现控制器方法整个Model实体类对象值为null,猛然发现原来是
  • 【小白笔记】 Linux 命令及其含义
  • vue ElementUI textarea在光标位置插入指定变量及校验
  • 边缘人工智能计算机
  • 亚远景侯亚文老师受邀出席PTC中国数字化转型精英汇,分享汽车研发破局“三擎”之道
  • K8S结合Istio深度实操
  • 【SQLMap】POST请求注入
  • 【C++实战⑪】解锁C++结构体:从基础到实战的进阶之旅
  • SAP-ABAP:SAP业务伙伴角色查询:BAPI_BUPA_ROLES_GET_2 详解与实践
  • 【openGLES】帧缓冲区对象frameBufferObject(FBO)
  • 端口转发神器Rinetd:轻量级安装与配置指南
  • Cursor+Claude编程+工作体会
  • [数据结构——lesson12.希尔排序]
  • Field II 超声成像仿真 1--得到Bmode图像
  • SpringBoot整合RustFS:全方位优化文件上传性能
  • 硬件(十一):EPIT、GPT、UART 外设配置
  • 趣味学RUST基础篇(OOP)
  • 微服务网关的bug
  • Rust 与 C/C++ 的特性对比
  • mac 安装hive
  • Nginx 从入门到进阶:反向代理、负载均衡与高性能实战指南
  • 微服务-nacos服务中心
  • uniApp开发XR-Frame微信小程序 | 动态加载与删除模型
  • AR 巡检在工业的应用|阿法龙XR云平台
  • eureka微服务注册问题
  • 【LangChain指南】大语言模型(LLMs)
  • 一台设备管理多个 GitHub 账号:从配置到切换的完整指南
  • K - 近邻(KNN)算法:基于约会数据集的分类任务全流程
  • 机器学习实战第四章 线性回归
  • 概率统计面试题2:随机抛掷两点到圆心距离较小值的期望