Well, this a complicated and fascinating subject, Secret Management. Consider secrets to be any type of credential: usernames and passwords, keys, tokens, AES keys, MFA seeds, or the 12 (recovery) words of crypto wallets and, why not, connections strings too.
Try keeping this data secure for 99% of its lifetime.
- at-rest: Wherever it's stored, it should never be in plain text format.
- in-transit: Whenever it's transferred, it should never be in raw format.
- in-memory: Whenever it's loaded into memory, it should never be vulnerable to profilers
In this specific case, the first thing to do ASAP is encrypt the credentials.
@Christophe's answer suggests the well-known pattern of comparing hashes instead of credentials in raw format. The problem is that hashes are not reversible. We lose the credentials, hence the capacity to create new connection strings.
Consider PosgreSQL's built-in encryption capabilities. They support at-rest and in transit encryption.
As for the in-memory security. The techniques depend on the stack, but some are quite generic. For example: don't store secrets in immutable types, nullify variables referencing secrets, or don't retain secrets in memory longer than necessary (no caches).