PostgreSQL函数用于最后插入的ID

在PostgreSQL中,可以通过使用INSERT语句的RETURNING子句来获取最后插入的ID,这与MS SQL中的SCOPE_IDENTITY()不同。示例展示了如何在当前会话中获取特定表和列的最后一个插入ID。
摘要由CSDN通过智能技术生成

本文翻译自:PostgreSQL function for last inserted ID

In PostgreSQL, how do I get the last id inserted into a table? 在PostgreSQL中,如何将最后一个id插入表中?

In MS SQL there is SCOPE_IDENTITY(). 在MS SQL中有SCOPE_IDENTITY()。

Please do not advise me to use something like this: 请不要建议我使用这样的东西:

select max(id) from table

#1楼

参考:https://stackoom.com/question/clWF/PostgreSQL函数用于最后插入的ID


#2楼

you can use RETURNING clause in INSERT statement,just like the following 您可以在INSERT语句中使用RETURNING子句,如下所示

wgzhao=
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FastAPI是一个轻量级的Web框架,用于Python,它使构建RESTful APIs变得简单。而PostgreSQL是强大的开源关系型数据库系统。在FastAPI中,我们可以使用SQLAlchemy或asyncpg等库来与PostgreSQL进行交互,包括数据的插入操作。以下是使用FastAPI和SQLAlchemy插入数据的基本步骤: 1. 安装依赖: 首先确保安装了`fastapi`, `sqlalchemy`, 和 `asyncpg`(如果用的是异步版本)。 ```bash pip install fastapi sqlalchemy asyncpg ``` 2. 创建数据库模型: 假设有一个名为`User`的表,你可以定义一个对应的 SQLAlchemy 模型: ```python from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) name = Column(String) email = Column(String, unique=True) ``` 3. 连接到数据库: 在FastAPI应用中,你可以创建一个异步数据库连接器: ```python from fastapi import FastAPI from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session app = FastAPI() engine = create_engine("postgresql://user:password@localhost/db_name") SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) async def get_db(): db = await scoped_session(SessionLocal) try: yield db finally: db.close() ``` 4. 插入数据: 在处理请求的视图函数中,你可以使用`get_db`获取数据库上下文,然后执行插入操作: ```python @app.post("/users/") async def create_user(user: User): async with get_db() as db: db.add(user) await db.commit() return {"message": "User created successfully"} ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值