MySQL .NET Connection String Options
The simplest MySQL connection string for C# is:
new MySqlConnection("Server=YOURSERVER;User ID=YOURUSERID;Password=YOURPASSWORD")
For all the other options, see the tables below. MySqlConnector supports most of Oracle’s Connector/NET connection options.
There are also several unique options that are supported only by MySqlConnector, a replacement for MySql.Data
that fixes bugs,
adds new features, and improves database access performance. Install it now.
Connection Options
These options specify how to connect and authenticate to a MySQL database.
Name | Default | Description |
---|---|---|
Server, Host, Data Source, DataSource, Address, Addr, Network Address | localhost | The host name or network address of the MySQL Server to which to connect. Multiple hosts can be specified in a comma-delimited list. On Unix-like systems, this can be a fully qualified path to a MySQL socket file, which will cause a Unix socket to be used instead of a TCP/IP socket. Only a single socket name can be specified. |
Port | 3306 | The TCP port on which MySQL Server is listening for connections. |
User ID, UserID, Username, Uid, User name, User | The MySQL user ID. | |
Password, pwd | The password for the MySQL user. For systems that use frequently-updated authentication tokens (such as Amazon Aurora RDS with IAM Authentication), leave this value empty, and set | |
Database, Initial Catalog | (Optional) The case-sensitive name of the initial database to use. This may be required if the MySQL user account only has access rights to particular databases on the server. | |
Load Balance, LoadBalance | RoundRobin | The load-balancing strategy to use when
|
Connection Protocol, ConnectionProtocol, Protocol | Socket | How to connect to the MySQL Server. This option has the following values:
|
Pipe Name, Pipe, PipeName | MYSQL | The name of the Windows named pipe to use to connect to the server. You must also set ConnectionProtocol=pipe to used named pipes. |
Connecting to Multiple Servers
The Server
option supports multiple comma-delimited host names.
The LoadBalance
option controls how load is distributed across backend servers.
Some of these options (RoundRobin
, LeastConnections
) only take effect if Pooling=True
; however Random
and FailOver
can be used with Pooling=False
.
RoundRobin
(default),Random
: A total ofMaximumPoolSize
connections will be opened, but they may be unevenly distributed across back ends.LeastConnections
: A total ofMaximumPoolSize
connections will be opened, and they will be evenly distributed across back ends. The active connections will be selected from the pool in least-recently-used order, which does not ensure even load across the back ends. You should setMaximumPoolSize
to the number of servers multiplied by the desired maximum number of open connections per backend server.Failover
: All connections will initially be made to the first server in the list. You should setMaximumPoolSize
to the maximum number of open connections you want per server.
SSL/TLS Options
These are the options that need to be used in order to configure a connection to use SSL/TLS.
Name | Default | Description |
---|---|---|
SSL Mode, SslMode | Preferred | This option has the following values:
|
Certificate File, CertificateFile | The path to a certificate file in PKCS #12 (.pfx) format containing a bundled Certificate and Private Key used for mutual authentication. To create a PKCS #12 bundle from a PEM encoded Certificate and Key, use If the certificate can't be loaded from a file path, leave this value empty and set | |
Certificate Password, CertificatePassword | The password for the certificate specified using the CertificateFile option. Not required if the certificate file is not password protected. | |
Certificate Store Location, CertificateStoreLocation | None | Specifies whether the connection should be encrypted with a certificate from the Certificate Store on the machine. The default value of None means the certificate store is not used; a value of CurrentUser or LocalMachine uses the specified store. |
Certificate Thumbprint, CertificateThumbprint | Specifies which certificate should be used from the certificate store specified in the setting above. This option must be used to indicate which certificate in the store should be used for authentication. | |
SSL Cert, SslCert, Ssl-Cert | The path to the client’s SSL certificate file in PEM format. SslKey must also be specified, and CertificateFile should not be. This option is not supported on netstandard2.0 . | |
SSL Key, SslKey, Ssl-Key | The path to the client’s SSL private key in PEM format. SslCert must also be specified, and CertificateFile should not be. | |
SSL CA, CA Certificate File, CACertificateFile, SslCa, Ssl-Ca | The path to a CA certificate file in a PEM Encoded (.pem) format. This should be used with To provide a custom callback to validate the remote certificate, leave this option empty and set | |
TLS Version, TlsVersion, Tls-Version | The TLS versions which may be used during TLS negotiation. The default value of null allows the OS to determine the TLS version to use (see documentation); this is the recommended setting. Otherwise, to restrict the versions that can be used, specify a comma-delimited list of versions taken from the following: TLS 1.0 , TLS 1.1. , TLS 1.2 , TLS 1.3 . (This option allows each version to be specified in a few different formats: Tls12 , Tlsv1.2 , TLS 1.2 , Tls v1.2 ; they are treated equivalently.) | |
TLS Cipher Suites,TlsCipherSuites | The TLS cipher suites which may be used during TLS negotiation. The default value (the empty string) allows the OS to determine the TLS cipher suites to use; this is the recommended setting. Otherwise, specify a comma-delimited list of TlsCipherSuite enum values to allow just those cipher suites. (This option is only supported on Linux when using .NET Core 3.1 or .NET 5.0 or later.) |
Connection Pooling Options
Connection pooling is enabled by default. These options are used to configure it.
Name | Default | Description |
---|---|---|
Pooling | true | Enables connection pooling. When pooling is enabled, MySqlConnection.Open /OpenAsync retrieves an open connection from the pool if one is available, and Close /Dispose /DisposeAsync returns the open connection to the pool. If there are no available connections in the pool, and the pool hasn’t reached MaximumPoolSize connections, a new connection will be opened; otherwise, the call to Open /OpenAsync blocks until a connection becomes available or ConnectionTimeout is reached. |
Connection Lifetime, ConnectionLifeTime | 0 | Connections that are returned to the pool will be closed if it’s been more than ConnectionLifeTime seconds since the connection was created. The default value of zero (0) means pooled connections will never incur a ConnectionLifeTime timeout. This can be useful when multiple database servers are being used, as it will force existing connections to be closed, which may spread load more evenly. |
Connection Reset, ConnectionReset | true | If true , all connections retrieved from the pool will have been reset. The default value of true ensures that the connection is in the same state whether it’s newly created or retrieved from the pool. A value of false avoids making an additional server round trip to reset the connection, but the connection state is not reset, meaning that session variables and other session state changes from any previous use of the connection are carried over. Additionally (if Connection Reset is false ), when MySqlConnection.Open returns a connection from the pool (instead of opening a new one), the connection may be invalid (and throw an exception on first use) if the server has closed the connection. |
Defer Connection Reset, DeferConnectionReset | This option was obsoleted in MySqlConnector 2.0. | |
Connection Idle Timeout, ConnectionIdleTimeout | 180 | The amount of time (in seconds) that a connection can remain idle in the pool. Any connection above MinimumPoolSize connections that is idle for longer than ConnectionIdleTimeout is subject to being closed by a background task. The background task runs every minute, or half of ConnectionIdleTimeout , whichever is more frequent. A value of zero (0) means pooled connections will never incur a ConnectionIdleTimeout, and if the pool grows to its maximum size, it will never get smaller. |
Minimum Pool Size, Min Pool Size, MinimumPoolSize, minpoolsize | 0 | The minimum number of connections to leave in the pool if ConnectionIdleTimeout is reached. |
Maximum Pool Size, Max Pool Size, MaximumPoolSize, maxpoolsize | 100 | The maximum number of connections allowed in the pool. |
DNS Check Interval, DnsCheckInterval | 0 | The number of seconds between checks for DNS changes, or 0 to disable periodic checks.
If the periodic check determines that one of the Server hostnames resolves to a different IP address, the pool will be cleared.
This is useful in HA scenarios where failover is accomplished by changing the IP address to which a hostname resolves.
Existing connections in the pool may have valid TCP connections to a server that is no longer responding or has been marked readonly;
clearing the pool (when DNS changes) forces all these existing connections to be reestablished. |
Other Options
These are the other options that MySqlConnector supports. They are set to sensible defaults and typically do not need to be tweaked.
Name | Default | Description |
---|---|---|
Allow Load Local Infile, AllowLoadLocalInfile | false | Allows the LOAD DATA LOCAL command to request files from the client. This is disabled by
default as a security precaution.
In order to use MySqlBulkLoader and set its Local property to true , you
must set this option to True in your connection string. |
Allow Public Key Retrieval, AllowPublicKeyRetrieval | false | If the user account uses sha256_password authentication, the password must be protected during transmission; TLS is the preferred mechanism for this,
but if it is not available then RSA public key encryption will be used. To specify the server’s RSA public key, use the ServerRSAPublicKeyFile connection
string setting, or set AllowPublicKeyRetrieval=True to allow the client to automatically request the public key from the server. Note that AllowPublicKeyRetrieval=True
could allow a malicious proxy to perform a MITM attack to get the plaintext password, so it is False by default and must be explicitly enabled. |
Allow User Variables, AllowUserVariables | false | Allows user-defined variables (prefixed with @ ) to be used in SQL statements. The default value (false )
only allows @ -prefixed names to refer to command parameters. |
Allow Zero DateTime, AllowZeroDateTime | false | If set to DATE , DATETIME and TIMESTAMP columns are returned as MySqlDateTime objects instead of DateTime .
This allows the special “zero” date value 0000-00-00 to be retrieved from the database. If false (the default)
date columns are returned as DateTime values, and an exception is thrown for unrepresentable dates. |
Application Name, ApplicationName | null | Sets the This connection string option is deprecated and is provided for backwards compatibility. Newer applications should
use |
Auto Enlist, AutoEnlist | true | If true (default), MySqlConnection will detect if there is an active TransactionScope when it's opened and automatically enlist in it. If false , connections must be manually enlisted by calling EnlistTransaction . |
Cancellation Timeout, CancellationTimeout | 2 | The length of time (in seconds) to wait for a query to be canceled when MySqlCommand.CommandTimeout expires, or zero for no timeout. If a response isn’t received from the server in this
time, the local socket will be closed and a MySqlException will be thrown. |
Character Set, CharSet, CharacterSet | utf8mb4 | MySqlConnector always uses utf8mb4 to send and receive strings from MySQL Server. This option may be specified (for backwards compatibility) but it will be ignored. |
Connection Timeout, Connect Timeout, ConnectionTimeout | 15 | The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error. |
Convert Zero DateTime, ConvertZeroDateTime | false | True to have MySqlDataReader.GetValue() and MySqlDataReader.GetDateTime() return DateTime.MinValue for date or datetime columns that have disallowed values. |
DateTime Kind, DateTimeKind | Unspecified | The DateTimeKind used when MySqlDataReader returns a DateTime . If set to Utc or Local ,
a MySqlException will be thrown if a DateTime command parameter has a Kind of Local or Utc ,
respectively. |
Default Command Timeout, Command Timeout, DefaultCommandTimeout | 30 | The length of time (in seconds) each command can execute before the query is cancelled on the server, or zero to disable timeouts. See the note in the Microsoft documentation for more explanation of how this is determined. |
GUID Format, GuidFormat | Default | Determines which column type (if any) should be read as a
|
Ignore Command Transaction, IgnoreCommandTransaction | false | If true , the value of MySqlCommand.Transaction is ignored when commands are executed.
This matches the Connector/NET behaviour and can make porting code easier. For more information, see Transaction Usage. |
Ignore Prepare, IgnorePrepare | false | If true , calls to MySqlCommand.Prepare(Async) are ignored (and will be no-ops).
This option is provided for backwards compatibility with MySQL Connector/NET (before 8.0.23) and should not be used. |
Interactive Session, Interactive, InteractiveSession | false | If true , the session wait_timeout variable is initialized from the global interactive_timeout value instead of the global wait_timeout value. |
Keep Alive, Keepalive | 0 | TCP Keepalive idle time (in seconds). A value of 0 indicates that the OS default keepalive settings are used; a value greater than 0 is the idle connection time (in seconds) before the first keepalive packet is sent. On Windows, this option is always supported. On non-Windows platforms, this option only takes effect in .NET Core 3.0 and later. For earlier versions of .NET Core, the OS Default keepalive settings are used instead. |
No Backslash Escapes, NoBackslashEscapes | false | If true , backslashes are not escaped in string parameters. Set this to true if the server’s SQL mode includes NO_BACKSLASH_ESCAPES . |
Old Guids, OldGuids | false | Obsolete; use the GuidFormat option instead. |
Persist Security Info, PersistSecurityInfo | false | When set to false or no (strongly recommended), security-sensitive information, such as the password, is not returned as part of the connection string if the connection is open or has ever been in an open state. Resetting the connection string resets all connection string values, including the password. Recognized values are true, false, yes, and no. |
Pipelining | true | When set to true , queries will be "pipelined" (when possible) by sending multiple packets to the server before waiting for a response. This improves performance (by reducing latency) but is not compatible with some servers (most notably Amazon Aurora RDS). Set to false to disable this behavior. |
Server Redirection Mode, ServerRedirectionMode | Disabled | Whether to use server redirection. The options include:
Server Redirection is supported by Azure Database for MySQL if the This option is only respected if |
Server RSA Public Key File, ServerRsaPublicKeyFile | For sha256_password authentication. See comments under AllowPublicKeyRetrieval . | |
Server SPN, ServerSPN | For MariaDB auth_gssapi_client authentication. Specifies the server’s Service Principal Name (to verify that authentication is occurring with the correct server). | |
Treat Tiny As Boolean, TreatTinyAsBoolean | true | When set to true , TINYINT(1) values are returned as booleans. Setting this to false causes TINYINT(1) to be returned as sbyte/byte. |
Use Affected Rows, UseAffectedRows | false | When false (default), the connection reports found rows instead of changed (affected) rows. Set to true to report only the number of rows actually changed by UPDATE or INSERT … ON DUPLICATE KEY UPDATE statements. |
Use Compression, Compress, UseCompression | false | If true (and if the server supports compression), compresses packets sent between client and server. This option is unlikely to be useful in practice unless there is a high-latency or low-bandwidth network link between the application and the database server. You should measure performance with and without this option to determine if it’s beneficial in your environment. |
Use XA Transactions, UseXaTransactions | true | When true (default), using TransactionScope or MySqlConnection.EnlistTransaction
will use a XA Transaction. This allows true
distributed transactions, but may not be compatible with server replication; there are other limitations.
When set to false , regular MySQL transactions are used, just like Connector/NET. |
Unsupported Options
These options are used by Connector/NET but not supported by MySqlConnector. In general, they should be removed from your connection string when migrating from Connector/NET to MySqlConnector.
Name | Default | Description |
---|---|---|
AllowBatch, Allow Batch | true | MySqlConnector always allows batch statements. |
CacheServerProperties, Cache Server Properties | MySqlConnector doesn’t need this optimization. | |
CheckParameters, Check Parameters | true | MySqlConnector always checks stored procedure parameters efficiently; there’s no need to disable this. |
CommandInterceptors, Command Interceptors | MySqlConnector doesn’t support this extensibility mechanism, which is not compatible with async operations. | |
DnsSrv, Dns-Srv | MySqlConnector doesn’t support discovering server addresses from DNS SRV records. | |
ExceptionInterceptors, Exception Interceptors | MySqlConnector doesn’t support this extensibility mechanism. | |
FunctionsReturnString, Functions Return String | false | Not supported. BLOBs are always returned as byte[] . |
IncludeSecurityAsserts, Include Security Asserts | false | Not supported. For partial trust environments. |
IntegratedSecurity, Integrated Security | false | Windows authentication is not supported. |
Logging | false | Use MySqlConnector logging (which is more flexible) instead. |
OldGetStringBehavior | false | This option is temporary in Connector/NET and unsupported in MySqlConnector. |
OldSyntax, Old Syntax, UseOldSyntax, Use Old Syntax | false | This option is deprecated in Connector/NET and unsupported in MySqlConnector. |
Password1, Password2, Password3 | MySqlConnector does not currently support multifactor authentication; see issue 1068. | |
ProcedureCacheSize, Procedure Cache Size, ProcedureCache, Procedure Cache | MySqlConnector places no limit on the amount of stored procedure metadata that is cached. It takes a very small amount of memory. | |
Replication | Not supported. | |
RespectBinaryFlags, Respect Binary Flags | true | The binary type of a column is always respected. |
SharedMemoryName, Shared Memory Name | true | Shared memory (on Windows) is not supported as a connection protocol. |
SshHostName, SshPort, SshUserName, SshPassword, SshKeyFile, SshPassPhrase | Connecting via SSH isn’t built into MySqlConnector, but can be set up easily by following these instructions. | |
SqlServerMode, Sql Server Mode | false | Not supported. |
TreatBlobsAsUtf8, Treat BLOBs as UTF8 | false | Not supported. BLOBs are always returned as byte[] . |
UsePerformanceMonitor, Use Performance Monitor, UserPerfMon, PerfMon | false | Not supported. |
UseUsageAdvisor, Use Usage Advisor, Usage Advisor | false | Not supported. |