You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PostgreSQL中仅在请求成功时,在CMD控制台显示通知?

How to Show Success Message Only When Database Request Succeeds in PostgreSQL

Let’s clear up a key misunderstanding first: the EXCEPTION clause in PostgreSQL is meant to handle errors, not signal successful completion. There’s no such exception as successful_completion—that’s not a valid condition for catching. Instead, here’s how to properly show your success message only when the update runs without issues (and optionally, only when rows were actually modified):

Basic Approach: Success on No Errors

If you just want to show the message when the UPDATE executes without throwing an error (even if no rows were updated), place the RAISE NOTICE right after the UPDATE statement. If an error occurs during the UPDATE, the code will jump to the EXCEPTION block (if included) and skip the success message.

DO $$
BEGIN
  UPDATE "user" SET age = 22, date_inscription = '2018-01-30' WHERE id = 154;
  
  -- This line runs ONLY if the UPDATE completed without errors
  RAISE NOTICE 'INFO : L''age et date inscription ont été mis à jour';

EXCEPTION
  -- Optional: Handle specific errors here (e.g., constraint violations)
  WHEN OTHERS THEN
    RAISE NOTICE 'Erreur lors de la mise à jour : %', SQLERRM;
    -- Uncomment below to re-throw the error if you want it to propagate
    -- RAISE;
END;
$$;

Better Approach: Success Only When Rows Are Modified

If you want the success message to appear only when at least one row was actually updated (not just when the query runs without error), use GET DIAGNOSTICS to check the number of rows affected:

DO $$
DECLARE
  rows_updated INTEGER;
BEGIN
  UPDATE "user" SET age = 22, date_inscription = '2018-01-30' WHERE id = 154;
  
  -- Get the number of rows affected by the UPDATE
  GET DIAGNOSTICS rows_updated = ROW_COUNT;
  
  IF rows_updated > 0 THEN
    RAISE NOTICE 'INFO : L''age et date inscription ont été mis à jour pour % ligne(s)', rows_updated;
  ELSE
    RAISE NOTICE 'INFO : Aucune ligne mise à jour (aucun utilisateur avec id = 154)';
  END IF;

EXCEPTION
  WHEN OTHERS THEN
    RAISE NOTICE 'Erreur lors de la mise à jour : %', SQLERRM;
END;
$$;

Key Notes:

  • I added quotes around "user" because it’s a reserved keyword in PostgreSQL—using it as a table name requires quoting.
  • The EXCEPTION block is optional, but including it lets you handle errors gracefully without the success message being shown when something goes wrong.
  • ROW_COUNT returns the number of rows affected by the last SQL statement, so it’s perfect for verifying if the update actually made changes.

内容的提问来源于stack exchange,提问作者user7722025

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:50:26