Table of Contents

Connection String Parameters

To connect to a database, the application provides a connection string which specifies parameters such as the host, the username, the password, etc. Connection strings have the form keyword1=value; keyword2=value; and are case-insensitive. Values containing special characters (e.g. semicolons) can be double-quoted. For more information, see the official doc page on connection strings.

Below are the connection string parameters which Npgsql understands, as well as some standard PostgreSQL environment variables.

Basic connection

ParameterDescriptionDefault
HostSpecifies the host name - and optionally port - on which PostgreSQL is running. Multiple hosts may be specified, see the docs for more info. If the value begins with a slash, it is used as the directory for the Unix-domain socket (specifying a Port is still required).Required
PortThe TCP port of the PostgreSQL server.5432
DatabaseThe PostgreSQL database to connect to.Same as Username
UsernameThe username to connect with. If not specified, the OS username will be used.PGUSER
PasswordThe password to connect with. Not required if using GSS/SSPI.PGPASSWORD
PassfilePath to a PostgreSQL password file (PGPASSFILE), from which the password is taken.PGPASSFILE

Security and encryption

ParameterDescriptionDefault
SSL ModeControls whether SSL is used, depending on server support. See docs for possible values and more info.Prefer
Trust Server CertificateWhether to trust the server certificate without validating it. See docs for more info.false
SSL CertificateLocation of a client certificate to be sent to the server. See docs.PGSSLCERT
SSL KeyLocation of a client key for a client certificate to be sent to the server.PGSSLKEY
SSL PasswordPassword for a key for a client certificate.
Root CertificateLocation of a CA certificate used to validate the server certificate.PGSSLROOTCERT
Check Certificate RevocationWhether to check the certificate revocation list during authentication.false
SSL NegotiationControls how SSL encryption is negotiated with the server, if SSL is used. Introduced in 9.0. See docs for possible values and more info.PGSSLNEGOTIATION
Channel BindingControl whether channel binding is used when authenticating with SASL. Introduced in 8.0.Prefer
Persist Security InfoGets or sets a Boolean value that indicates if security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state.false
Kerberos Service NameThe Kerberos service name to be used for authentication. See docs for more info.postgres
Include RealmThe Kerberos realm to be used for authentication. See docs for more info.
Include Error DetailWhen enabled, PostgreSQL error and notice details are included on PostgresException.Detail and PostgresNotice.Detail. These can contain sensitive data.false
Log ParametersWhen enabled, parameter values are logged when commands are executed.false

Pooling

ParameterDescriptionDefault
PoolingWhether connection pooling should be used.true
Minimum Pool SizeThe minimum connection pool size.0
Maximum Pool SizeThe maximum connection pool size.100 since 3.1, 20 previously
Connection Idle LifetimeThe time (in seconds) to wait before closing idle connections in the pool if the count of all connections exceeds Minimum Pool Size. Introduced in 3.1.300
Connection Pruning IntervalHow many seconds the pool waits before attempting to prune idle connections that are beyond idle lifetime (see Connection Idle Lifetime). Introduced in 3.1.10
Connection LifetimeThe total maximum lifetime of connections (in seconds). Connections which have exceeded this value will be destroyed instead of returned from the pool. This is useful in clustered configurations to force load balancing between a running server and a server just brought online.3600 (1 hour), in Npgsql 8.0 and before - 0 (disabled)

Timeouts and keepalive

ParameterDescriptionDefault
TimeoutThe time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error.15
Command TimeoutThe time to wait (in seconds) while trying to execute a command before terminating the attempt and generating an error. Set to zero for infinity.30
Cancellation TimeoutThe time to wait (in milliseconds) while trying to read a response for a cancellation request for a timed out or cancelled query, before terminating the attempt and generating an error. -1 skips the wait, 0 means infinite wait. Introduced in 5.0.2000
KeepaliveThe number of seconds of connection inactivity before Npgsql sends a keepalive query.0 (disabled)
Tcp KeepaliveWhether to use TCP keepalive with system defaults if overrides isn't specified.false
Tcp Keepalive TimeThe number of seconds of connection inactivity before a TCP keepalive query is sent. Use of this option is discouraged, use KeepAlive instead if possible.0 (disabled)
Tcp Keepalive IntervalThe interval, in seconds, between when successive keep-alive packets are sent if no acknowledgement is received. Tcp KeepAlive Time must be non-zero as well.value of Tcp Keepalive Time

Performance

ParameterDescriptionDefault
Max Auto PrepareThe maximum number SQL statements that can be automatically prepared at any given point. Beyond this number the least-recently-used statement will be recycled. Zero disables automatic preparation.0
Auto Prepare Min UsagesThe minimum number of usages an SQL statement is used before it's automatically prepared.5
Read Buffer SizeDetermines the size of the internal buffer Npgsql uses when reading. Increasing may improve performance if transferring large values from the database.8192
Write Buffer SizeDetermines the size of the internal buffer Npgsql uses when writing. Increasing may improve performance if transferring large values to the database.8192
Socket Receive Buffer SizeDetermines the size of socket receive buffer.System-dependent
Socket Send Buffer SizeDetermines the size of socket send buffer.System-dependent
No Reset On CloseImproves performance in some cases by not resetting the connection state when it is returned to the pool, at the cost of leaking state. Use only if benchmarking shows a performance improvementfalse

Failover and load balancing

For more information, see the dedicated docs page.

ParameterDescriptionDefault
Target Session AttributesDetermines the preferred PostgreSQL target server type.PGTARGETSESSIONATTRS, Any
Load Balance HostsEnables balancing between multiple hosts by round-robin.false
Host Recheck SecondsControls for how long the host's cached state will be considered as valid.10

Misc

ParameterDescriptionDefault
Options1Specifies any valid PostgreSQL connection options (e.g. Options=-c synchronous_commit=local). Introduced in 5.0.PGOPTIONS
Application NameThe optional application name parameter to be sent to the backend during connection initiation.
EnlistWhether to enlist in an ambient TransactionScope.true
Search PathSets the schema search path.
Client EncodingGets or sets the client_encoding parameter.PGCLIENTENCODING, UTF8
EncodingGets or sets the .NET encoding that will be used to encode/decode PostgreSQL string data.UTF8
TimezoneGets or sets the session timezone.PGTZ
Array Nullability ModeConfigure the way arrays of value types are returned when requested as object instances. Possible values are: Never (arrays of value types are always returned as non-nullable arrays), Always (arrays of value types are always returned as nullable arrays) and PerInstance (the type of array that gets returned is determined at runtime).Never

1The Options connection string parameter is essentially the string of command line options that get passed to the postgres program when the process is started. It is most commonly used to set named run-time parameters via the -c option but other options can be used too (although not all of them make sense in that context). Setting multiple options is possible by separating them with a space character. Space and backslash characters in option values need to be escaped by prefixing a backslash character. Example: Options=-c default_transaction_isolation=serializable -c default_transaction_deferrable=on -c foo.bar=My\\ Famous\\\\Thing

Obsolete/removed

ParameterDescriptionDefault
Load Table CompositesLoad table composite type definitions, and not just free-standing composite types. Obsoleted in 9.0, use NpgsqlDataSourceBuilder.ConfigureTypeLoading().false
Server Compatibility ModeA compatibility mode for special PostgreSQL server types. Currently "Redshift" is supported, as well as "NoTypeLoading", which will bypass the normal type loading mechanism from the PostgreSQL catalog tables and supports a hardcoded list of basic types. Obsoleted in 9.0, use NpgsqlDataSourceBuilder.ConfigureTypeLoading().none
Internal Command TimeoutThe time to wait (in seconds) while trying to execute an internal command before terminating the attempt and generating an error. -1 uses CommandTimeout, 0 means no timeout.-1
EF Template DatabaseThe database template to specify when creating a database in non-core Entity Framework. Removed in 8.0.template1
EF Admin DatabaseThe database admin to specify when creating and dropping a database in non-core Entity Framework. Removed in 8.0.template1

Environment variables

In addition to the connection string parameters above, Npgsql also recognizes the standard PostgreSQL environment variables below. This helps Npgsql-based applications behave similar to other, non-.NET PostgreSQL client applications. The PostgreSQL doc page on environment variables recognized by libpq can be found here.

Environment variableDescription
PGUSERBehaves the same as the user connection parameter.
PGPASSWORDBehaves the same as the password connection parameter. Use of this environment variable is not recommended for security reasons, as some operating systems allow non-root users to see process environment variables via ps; instead consider using a password file (see Section 33.15).
PGPASSFILEBehaves the same as the passfile connection parameter.
PGSSLCERTBehaves the same as the sslcert connection parameter.
PGSSLKEYBehaves the same as the sslkey connection parameter.
PGSSLROOTCERTBehaves the same as the sslrootcert connection parameter.
PGCLIENTENCODINGBehaves the same as the client_encoding connection parameter.
PGTZSets the default time zone. (Equivalent to SET timezone TO ....)
PGOPTIONSBehaves the same as the options connection parameter.
PGSSLNEGOTIATIONBehaves the same as the sslnegotiation connection parameter.
close