PostgreSQL connection string format
Host=localhost;Port=5432;Database=shop;Username=postgres;Password=secret
Examples
| Case | Connection string |
|---|---|
| Local server | Host=localhost;Database=shop;Username=postgres;Password=secret |
| Docker Compose (service named db) | Host=db;Port=5432;Database=shop;Username=app;Password=secret |
| Require TLS (most hosted servers) | Host=myserver.postgres.database.azure.com;Database=shop;Username=app;Password=secret;SSL Mode=Require |
| Primary and standby, connect to the primary | Host=pg1,pg2;Database=shop;Username=app;Password=secret;Target Session Attributes=primary |
| Bigger pool, detailed errors while developing | Host=localhost;Database=shop;Username=app;Password=secret;Maximum Pool Size=200;Include Error Detail=true |
Every example on this page is checked with Npgsql itself. Replace the passwords with your own, and keep real ones out of source control.
postgres:// URLs
Heroku, Render, Supabase and Railway give you a URL such as postgres://user:pass@host:5432/db?sslmode=require. Npgsql does not read URLs: it throws an ArgumentException ("Format of the initialization string does not conform to specification", or "Couldn't set ..." when the URL has a query string). Paste the URL in "Check a string" above and the page writes the keyword form. The user and password in a URL are percent-encoded; the keyword form uses the plain text.
SSL Mode and TLS
Npgsql's default is SSL Mode=Prefer: TLS if the server offers it. Use Require to refuse unencrypted connections; VerifyFull also checks the certificate and host name. Azure Database for PostgreSQL and most cloud servers require TLS.
Where to keep it
Put it under ConnectionStrings in appsettings.json and read it with builder.Configuration.GetConnectionString("Default"). Keep passwords out of the file: user secrets in development, and an environment variable (ConnectionStrings__Default) or a secret store in production.
FAQ
Why does Npgsql reject my postgres:// connection string?
Npgsql only reads the keyword format. Convert postgres://user:pass@host:5432/db to Host=host;Port=5432;Database=db;Username=user;Password=pass (this page does it).
What is the default port?
5432. Add Port=... only when the server listens elsewhere.
How do I use it with EF Core?
Add Npgsql.EntityFrameworkCore.PostgreSQL and call options.UseNpgsql(builder.Configuration.GetConnectionString("Default")) in AddDbContext.
Username or User ID?
Username, User ID, User Name, UserId and UID all work; Npgsql writes Username.
Other databases
- SQL Server connection string
- MySQL connection string
- SQLite connection string
- MongoDB connection string
- Redis connection string
- Connection string builder for every database