Class NpgsqlConnection
- Namespace
- Npgsql
- Assembly
- Npgsql.dll
This class represents a connection to a PostgreSQL server.
public sealed class NpgsqlConnection : DbConnection, IDbConnection, IAsyncDisposable, ICloneable, IComponent, IDisposable
- Inheritance
-
NpgsqlConnection
- Implements
- Inherited Members
Constructors
NpgsqlConnection()
Initializes a new instance of the NpgsqlConnection class.
public NpgsqlConnection()
NpgsqlConnection(string?)
Initializes a new instance of NpgsqlConnection with the given connection string.
public NpgsqlConnection(string? connectionString)
Parameters
connectionString
stringThe connection used to open the PostgreSQL database.
Fields
DefaultPort
The default TCP/IP port for PostgreSQL.
public const int DefaultPort = 5432
Field Value
Properties
CanCreateBatch
Gets a value that indicates whether this DbConnection instance supports the DbBatch class.
public override bool CanCreateBatch { get; }
Property Value
CommandTimeout
Gets the time (in seconds) to wait while trying to execute a command before terminating the attempt and generating an error.
public int CommandTimeout { get; }
Property Value
- int
The time (in seconds) to wait for a command to complete. The default value is 30 seconds.
ConnectionString
Gets or sets the string used to connect to a PostgreSQL database. See the manual for details.
public override string ConnectionString { get; set; }
Property Value
- string
The connection string that includes the server name, the database name, and other parameters needed to establish the initial connection. The default value is an empty string.
ConnectionTimeout
Gets the time (in seconds) to wait while trying to establish a connection before terminating the attempt and generating an error.
public override int ConnectionTimeout { get; }
Property Value
- int
The time (in seconds) to wait for a connection to open. The default value is 15 seconds.
DataSource
Gets the string identifying the database server (host and port)
public override string DataSource { get; }
Property Value
- string
The name of the database server (host and port). If the connection uses a Unix-domain socket, the path to that socket is returned. The default value is the empty string.
Database
Gets the name of the current database or the database to be used after a connection is opened.
public override string Database { get; }
Property Value
- string
The name of the current database or the name of the database to be used after a connection is opened. The default value is the empty string.
DbProviderFactory
DB provider factory.
protected override DbProviderFactory DbProviderFactory { get; }
Property Value
FullState
Gets the current state of the connection.
[Browsable(false)]
public ConnectionState FullState { get; }
Property Value
- ConnectionState
A bitwise combination of the ConnectionState values. The default is Closed.
GlobalTypeMapper
The global type mapper, which contains defaults used by all new connections. Modify mappings on this mapper to affect your entire application.
[Obsolete("Global-level type mapping has been replaced with data source mapping, see the 7.0 release notes.")]
public static INpgsqlTypeMapper GlobalTypeMapper { get; }
Property Value
HasIntegerDateTimes
Reports whether the backend uses the newer integer timestamp representation. Note that the old floating point representation is not supported. Meant for use by type plugins (e.g. NodaTime)
[Browsable(false)]
public bool HasIntegerDateTimes { get; }
Property Value
Host
Backend server host name.
[Browsable(true)]
public string? Host { get; }
Property Value
Port
Backend server port.
[Browsable(true)]
public int Port { get; }
Property Value
PostgreSqlVersion
The version of the PostgreSQL server we're connected to.
This can only be called when the connection is open.
In case of a development or pre-release version this field will contain the version of the next version to be released from this branch.
[Browsable(false)]
public Version PostgreSqlVersion { get; }
Property Value
PostgresParameters
Holds all PostgreSQL parameters received for this connection. Is updated if the values change (e.g. as a result of a SET command).
[Browsable(false)]
public IReadOnlyDictionary<string, string> PostgresParameters { get; }
Property Value
ProcessID
Process id of backend server. This can only be called when there is an active connection.
[Browsable(false)]
public int ProcessID { get; }
Property Value
ProvideClientCertificatesCallback
Selects the local Secure Sockets Layer (SSL) certificate used for authentication.
public ProvideClientCertificatesCallback? ProvideClientCertificatesCallback { get; set; }
Property Value
Remarks
ProvidePasswordCallback
Gets or sets the delegate used to generate a password for new database connections.
[Obsolete("Use NpgsqlDataSourceBuilder.UsePeriodicPasswordProvider or inject passwords directly into NpgsqlDataSource.Password")]
public ProvidePasswordCallback? ProvidePasswordCallback { get; set; }
Property Value
Remarks
This delegate is executed when a new database connection is opened that requires a password.
The Password and Passfile connection string properties have precedence over this delegate: it will not be executed if a password is specified, or if the specified or default Passfile contains a valid entry.
Due to connection pooling this delegate is only executed when a new physical connection is opened, not when reusing a connection that was previously opened from the pool.
ServerVersion
The PostgreSQL server version as returned by the server_version option.
public override string ServerVersion { get; }
Property Value
State
Gets whether the current state of the connection is Open or Closed
[Browsable(false)]
public override ConnectionState State { get; }
Property Value
- ConnectionState
ConnectionState.Open, ConnectionState.Closed or ConnectionState.Connecting
Timezone
The connection's timezone as reported by PostgreSQL, in the IANA/Olson database format.
[Browsable(false)]
public string Timezone { get; }
Property Value
TypeMapper
Connection-level type mapping is no longer supported. See the 7.0 release notes for configuring type mapping on NpgsqlDataSource.
[Obsolete("Connection-level type mapping is no longer supported. See the 7.0 release notes for configuring type mapping on NpgsqlDataSource.", true)]
public INpgsqlTypeMapper TypeMapper { get; }
Property Value
UserCertificateValidationCallback
When using SSL/TLS, this is a callback that allows customizing how the PostgreSQL-provided certificate is verified. This is an advanced API, consider using VerifyFull or VerifyCA instead.
public RemoteCertificateValidationCallback? UserCertificateValidationCallback { get; set; }
Property Value
Remarks
Cannot be used in conjunction with Disable, VerifyCA and VerifyFull.
UserName
User name.
public string? UserName { get; }
Property Value
Methods
BeginBinaryExport(string)
Begins a binary COPY TO STDOUT operation, a high-performance data export mechanism from a PostgreSQL table.
public NpgsqlBinaryExporter BeginBinaryExport(string copyToCommand)
Parameters
copyToCommand
stringA COPY TO STDOUT SQL command
Returns
- NpgsqlBinaryExporter
A NpgsqlBinaryExporter which can be used to read rows and columns
Remarks
BeginBinaryExportAsync(string, CancellationToken)
Begins a binary COPY TO STDOUT operation, a high-performance data export mechanism from a PostgreSQL table.
public Task<NpgsqlBinaryExporter> BeginBinaryExportAsync(string copyToCommand, CancellationToken cancellationToken = default)
Parameters
copyToCommand
stringA COPY TO STDOUT SQL command
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
- Task<NpgsqlBinaryExporter>
A NpgsqlBinaryExporter which can be used to read rows and columns
Remarks
BeginBinaryImport(string)
Begins a binary COPY FROM STDIN operation, a high-performance data import mechanism to a PostgreSQL table.
public NpgsqlBinaryImporter BeginBinaryImport(string copyFromCommand)
Parameters
copyFromCommand
stringA COPY FROM STDIN SQL command
Returns
- NpgsqlBinaryImporter
A NpgsqlBinaryImporter which can be used to write rows and columns
Remarks
BeginBinaryImportAsync(string, CancellationToken)
Begins a binary COPY FROM STDIN operation, a high-performance data import mechanism to a PostgreSQL table.
public Task<NpgsqlBinaryImporter> BeginBinaryImportAsync(string copyFromCommand, CancellationToken cancellationToken = default)
Parameters
copyFromCommand
stringA COPY FROM STDIN SQL command
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
- Task<NpgsqlBinaryImporter>
A NpgsqlBinaryImporter which can be used to write rows and columns
Remarks
BeginDbTransaction(IsolationLevel)
Begins a database transaction with the specified isolation level.
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
Parameters
isolationLevel
IsolationLevelThe isolation level under which the transaction should run.
Returns
- DbTransaction
A DbTransaction object representing the new transaction.
Remarks
Nested transactions are not supported.
BeginDbTransactionAsync(IsolationLevel, CancellationToken)
Asynchronously begins a database transaction.
protected override ValueTask<DbTransaction> BeginDbTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken)
Parameters
isolationLevel
IsolationLevelThe isolation level under which the transaction should run.
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
- ValueTask<DbTransaction>
A task whose Result property is an object representing the new transaction.
Remarks
Nested transactions are not supported.
BeginRawBinaryCopy(string)
Begins a raw binary COPY operation (TO STDOUT or FROM STDIN), a high-performance data export/import mechanism to a PostgreSQL table. Note that unlike the other COPY API methods, BeginRawBinaryCopy(string) doesn't implement any encoding/decoding and is unsuitable for structured import/export operation. It is useful mainly for exporting a table as an opaque blob, for the purpose of importing it back later.
public NpgsqlRawCopyStream BeginRawBinaryCopy(string copyCommand)
Parameters
copyCommand
stringA COPY TO STDOUT or COPY FROM STDIN SQL command
Returns
- NpgsqlRawCopyStream
A NpgsqlRawCopyStream that can be used to read or write raw binary data.
Remarks
BeginRawBinaryCopyAsync(string, CancellationToken)
Begins a raw binary COPY operation (TO STDOUT or FROM STDIN), a high-performance data export/import mechanism to a PostgreSQL table. Note that unlike the other COPY API methods, BeginRawBinaryCopyAsync(string, CancellationToken) doesn't implement any encoding/decoding and is unsuitable for structured import/export operation. It is useful mainly for exporting a table as an opaque blob, for the purpose of importing it back later.
public Task<NpgsqlRawCopyStream> BeginRawBinaryCopyAsync(string copyCommand, CancellationToken cancellationToken = default)
Parameters
copyCommand
stringA COPY TO STDOUT or COPY FROM STDIN SQL command
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
- Task<NpgsqlRawCopyStream>
A NpgsqlRawCopyStream that can be used to read or write raw binary data.
Remarks
BeginTextExport(string)
Begins a textual COPY TO STDOUT operation, a data export mechanism from a PostgreSQL table.
It is the user's responsibility to parse the textual input according to the format specified
in copyToCommand
.
public TextReader BeginTextExport(string copyToCommand)
Parameters
copyToCommand
stringA COPY TO STDOUT SQL command
Returns
- TextReader
A TextReader that can be used to read textual data.
Remarks
BeginTextExportAsync(string, CancellationToken)
Begins a textual COPY TO STDOUT operation, a data export mechanism from a PostgreSQL table.
It is the user's responsibility to parse the textual input according to the format specified
in copyToCommand
.
public Task<TextReader> BeginTextExportAsync(string copyToCommand, CancellationToken cancellationToken = default)
Parameters
copyToCommand
stringA COPY TO STDOUT SQL command
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
- Task<TextReader>
A TextReader that can be used to read textual data.
Remarks
BeginTextImport(string)
Begins a textual COPY FROM STDIN operation, a data import mechanism to a PostgreSQL table.
It is the user's responsibility to send the textual input according to the format specified
in copyFromCommand
.
public TextWriter BeginTextImport(string copyFromCommand)
Parameters
copyFromCommand
stringA COPY FROM STDIN SQL command
Returns
- TextWriter
A TextWriter that can be used to send textual data.
Remarks
BeginTextImportAsync(string, CancellationToken)
Begins a textual COPY FROM STDIN operation, a data import mechanism to a PostgreSQL table.
It is the user's responsibility to send the textual input according to the format specified
in copyFromCommand
.
public Task<TextWriter> BeginTextImportAsync(string copyFromCommand, CancellationToken cancellationToken = default)
Parameters
copyFromCommand
stringA COPY FROM STDIN SQL command
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
- Task<TextWriter>
A TextWriter that can be used to send textual data.
Remarks
BeginTransaction()
Begins a database transaction.
public NpgsqlTransaction BeginTransaction()
Returns
- NpgsqlTransaction
A NpgsqlTransaction object representing the new transaction.
Remarks
Nested transactions are not supported. Transactions created by this method will have the ReadCommitted isolation level.
BeginTransaction(IsolationLevel)
Begins a database transaction with the specified isolation level.
public NpgsqlTransaction BeginTransaction(IsolationLevel level)
Parameters
level
IsolationLevelThe isolation level under which the transaction should run.
Returns
- NpgsqlTransaction
A NpgsqlTransaction object representing the new transaction.
Remarks
Nested transactions are not supported.
BeginTransactionAsync(IsolationLevel, CancellationToken)
Asynchronously begins a database transaction.
public ValueTask<NpgsqlTransaction> BeginTransactionAsync(IsolationLevel level, CancellationToken cancellationToken = default)
Parameters
level
IsolationLevelThe isolation level under which the transaction should run.
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
- ValueTask<NpgsqlTransaction>
A task whose Result property is an object representing the new transaction.
Remarks
Nested transactions are not supported.
BeginTransactionAsync(CancellationToken)
Asynchronously begins a database transaction.
public ValueTask<NpgsqlTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
- ValueTask<NpgsqlTransaction>
A task whose Result property is an object representing the new transaction.
Remarks
Nested transactions are not supported. Transactions created by this method will have the ReadCommitted isolation level.
ChangeDatabase(string)
This method changes the current database by disconnecting from the actual database and connecting to the specified.
public override void ChangeDatabase(string dbName)
Parameters
dbName
stringThe name of the database to use in place of the current database.
ClearAllPools()
Clear all connection pools. All idle physical connections in all pools are immediately closed, and any busy connections which were opened before ClearAllPools() was called will be closed when returned to their pool.
public static void ClearAllPools()
ClearPool(NpgsqlConnection)
Clears the connection pool. All idle physical connections in the pool of the given connection are immediately closed, and any busy connections which were opened before ClearPool(NpgsqlConnection) was called will be closed when returned to the pool.
public static void ClearPool(NpgsqlConnection connection)
Parameters
connection
NpgsqlConnection
CloneWith(string)
Clones this connection, replacing its connection string with the given one. This allows creating a new connection with the same security information (password, SSL callbacks) while changing other connection parameters (e.g. database or pooling)
public NpgsqlConnection CloneWith(string connectionString)
Parameters
connectionString
string
Returns
Close()
Releases the connection. If the connection is pooled, it will be returned to the pool and made available for re-use. If it is non-pooled, the physical connection will be closed.
public override void Close()
CloseAsync()
Releases the connection. If the connection is pooled, it will be returned to the pool and made available for re-use. If it is non-pooled, the physical connection will be closed.
public override Task CloseAsync()
Returns
CreateBatch()
Returns a new instance of the provider's class that implements the DbBatch class.
public NpgsqlBatch CreateBatch()
Returns
- NpgsqlBatch
A new instance of DbBatch.
CreateCommand()
Creates and returns a NpgsqlCommand object associated with the NpgsqlConnection.
public NpgsqlCommand CreateCommand()
Returns
- NpgsqlCommand
A NpgsqlCommand object.
CreateDbBatch()
When overridden in a derived class, returns a new instance of the provider's class that implements the DbBatch class.
protected override DbBatch CreateDbBatch()
Returns
CreateDbCommand()
Creates and returns a DbCommand object associated with the DbConnection.
protected override DbCommand CreateDbCommand()
Returns
Dispose(bool)
Releases all resources used by the NpgsqlConnection.
protected override void Dispose(bool disposing)
Parameters
disposing
booltrue when called from Dispose(bool); false when being called from the finalizer.
DisposeAsync()
Releases all resources used by the NpgsqlConnection.
public override ValueTask DisposeAsync()
Returns
EnlistTransaction(Transaction?)
Enlist transaction.
public override void EnlistTransaction(Transaction? transaction)
Parameters
transaction
Transaction
GetSchema()
Returns the supported collections
public override DataTable GetSchema()
Returns
GetSchema(string?)
Returns the schema collection specified by the collection name.
public override DataTable GetSchema(string? collectionName)
Parameters
collectionName
stringThe collection name.
Returns
- DataTable
The collection specified.
GetSchema(string?, string?[]?)
Returns the schema collection specified by the collection name filtered by the restrictions.
public override DataTable GetSchema(string? collectionName, string?[]? restrictions)
Parameters
collectionName
stringThe collection name.
restrictions
string[]The restriction values to filter the results. A description of the restrictions is contained in the Restrictions collection.
Returns
- DataTable
The collection specified.
GetSchemaAsync(string, string?[]?, CancellationToken)
Asynchronously returns the schema collection specified by the collection name filtered by the restrictions.
public override Task<DataTable> GetSchemaAsync(string collectionName, string?[]? restrictions, CancellationToken cancellationToken = default)
Parameters
collectionName
stringThe collection name.
restrictions
string[]The restriction values to filter the results. A description of the restrictions is contained in the Restrictions collection.
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
GetSchemaAsync(string, CancellationToken)
Asynchronously returns the schema collection specified by the collection name.
public override Task<DataTable> GetSchemaAsync(string collectionName, CancellationToken cancellationToken = default)
Parameters
collectionName
stringThe collection name.
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
GetSchemaAsync(CancellationToken)
Asynchronously returns the supported collections.
public override Task<DataTable> GetSchemaAsync(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
Open()
Opens a database connection with the property settings specified by the ConnectionString.
public override void Open()
OpenAsync(CancellationToken)
This is the asynchronous version of Open().
public override Task OpenAsync(CancellationToken cancellationToken)
Parameters
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
- Task
A task representing the asynchronous operation.
Remarks
Do not invoke other methods and properties of the NpgsqlConnection object until the returned Task is complete.
ReloadTypes()
Flushes the type cache for this connection's connection string and reloads the types for this connection only. Type changes will appear for other connections only after they are re-opened from the pool.
public void ReloadTypes()
ReloadTypesAsync()
Flushes the type cache for this connection's connection string and reloads the types for this connection only. Type changes will appear for other connections only after they are re-opened from the pool.
public Task ReloadTypesAsync()
Returns
UnprepareAll()
Unprepares all prepared statements on this connection.
public void UnprepareAll()
Wait()
Waits until an asynchronous PostgreSQL messages (e.g. a notification) arrives, and exits immediately. The asynchronous message is delivered via the normal events (Notification, Notice).
public void Wait()
Wait(int)
Waits until an asynchronous PostgreSQL messages (e.g. a notification) arrives, and exits immediately. The asynchronous message is delivered via the normal events (Notification, Notice).
public bool Wait(int timeout)
Parameters
timeout
intThe time-out value, in milliseconds, passed to ReceiveTimeout. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.
Returns
- bool
true if an asynchronous message was received, false if timed out.
Wait(TimeSpan)
Waits until an asynchronous PostgreSQL messages (e.g. a notification) arrives, and exits immediately. The asynchronous message is delivered via the normal events (Notification, Notice).
public bool Wait(TimeSpan timeout)
Parameters
timeout
TimeSpanThe time-out value is passed to ReceiveTimeout.
Returns
- bool
true if an asynchronous message was received, false if timed out.
WaitAsync(int, CancellationToken)
Waits asynchronously until an asynchronous PostgreSQL messages (e.g. a notification) arrives, and exits immediately. The asynchronous message is delivered via the normal events (Notification, Notice).
public Task<bool> WaitAsync(int timeout, CancellationToken cancellationToken = default)
Parameters
timeout
intThe time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
WaitAsync(CancellationToken)
Waits asynchronously until an asynchronous PostgreSQL messages (e.g. a notification) arrives, and exits immediately. The asynchronous message is delivered via the normal events (Notification, Notice).
public Task WaitAsync(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
WaitAsync(TimeSpan, CancellationToken)
Waits asynchronously until an asynchronous PostgreSQL messages (e.g. a notification) arrives, and exits immediately. The asynchronous message is delivered via the normal events (Notification, Notice).
public Task<bool> WaitAsync(TimeSpan timeout, CancellationToken cancellationToken = default)
Parameters
timeout
TimeSpanThe time-out value as TimeSpan
cancellationToken
CancellationTokenAn optional token to cancel the asynchronous operation. The default value is None.
Returns
Events
Notice
Fires when PostgreSQL notices are received from PostgreSQL.
public event NoticeEventHandler? Notice
Event Type
Remarks
PostgreSQL notices are non-critical messages generated by PostgreSQL, either as a result of a user query (e.g. as a warning or informational notice), or due to outside activity (e.g. if the database administrator initiates a "fast" database shutdown).
Note that notices are very different from notifications (see the Notification event).
Notification
Fires when PostgreSQL notifications are received from PostgreSQL.
public event NotificationEventHandler? Notification
Event Type
Remarks
PostgreSQL notifications are sent when your connection has registered for notifications on a specific channel via the LISTEN command. NOTIFY can be used to generate such notifications, allowing for an inter-connection communication channel.
Note that notifications are very different from notices (see the Notice event).