SQLAlchemy Layer - SQL Expression 说明

请添加图片描述

Expressions let you compose SQL statements by building Python objects.

  • Instead of sending raw SQL (using the Engine), we can compose python objects to compose SQL expressions, instead.
  • SQL Expressions still involves using the knowing SQL to interact with the database.
todos = Table('todos',...)

ins = todos.insert().values(
	description = 'Clean my room',
	completed = False
)

s = select([todos])

conn = engine.connect()
result = conn.execute(ins)
result = conn.execute(s)

result.close()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLAlchemy 中,可以使用 `func.group_concat()` 函数来实现类似于 MySQL 中的 `GROUP_CONCAT` 函数的功能。`func.group_concat()` 函数可以将一个列的所有值拼接成一个字符串,并且可以指定分隔符。 下面是一个简单的例子,假设有一个 `Book` 表格,其中包含了 `id` 和 `title` 两个列,我们想要将所有的书名拼接成一个字符串并以 `,` 分隔: ```python from sqlalchemy import create_engine, Column, Integer, String, func from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('mysql+pymysql://user:password@host:port/database', echo=True) Session = sessionmaker(bind=engine) session = Session() Base = declarative_base() class Book(Base): __tablename__ = 'books' id = Column(Integer, primary_key=True) title = Column(String(255)) result = session.query(func.group_concat(Book.title, separator=',')).scalar() print(result) ``` 在上面的代码中,我们使用 `func.group_concat()` 函数将 `Book` 表格中的所有书名拼接成一个字符串,并以 `,` 分隔。`func.group_concat()` 函数的第一个参数是要拼接的列,第二个参数是分隔符(可选,默认为 `,`)。`session.query(func.group_concat(Book.title, separator=','))` 会生成一个 SQL 查询语句类似于 `SELECT GROUP_CONCAT(title SEPARATOR ',') FROM books`,使用 `scalar()` 方法可以获取查询结果。 希望这个例子能够帮助你理解如何在 SQLAlchemy 中使用 `func.group_concat()` 函数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值