Compared to MySql.Data (i.e., Oracle’s MySQL Connector/NET), MySqlConnector has the following benefits:
Async
methods (see bugs fixed)DbBatch
, DateOnly
, DbDataSource
and other new .NET featuresMySqlConnector supports the same core API as MySQL Connector/NET, but the classes are in a different namespace. Change using MySql.Data.MySqlClient;
to using MySqlConnector;
.
The MySqlClientFactory
type is named MySqlConnectorFactory
in MySqlConnector.
In a .NET Framework application, make the following app.config
change to register MySqlConnector instead of MySql.Data.
<system.data>
<DbProviderFactories>
<!-- REMOVE THIS -->
<!-- add name="MySQL Data Provider"
invariant="MySql.Data.MySqlClient"
description=".Net Framework Data Provider for MySQL"
type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=9.4.0.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" / -->
<!-- ADD THIS -->
<add name="MySqlConnector"
invariant="MySqlConnector"
description="MySQL Connector for .NET"
type="MySqlConnector.MySqlConnectorFactory, MySqlConnector, Culture=neutral, PublicKeyToken=d33d3e53aa5f8c92" />
</DbProviderFactories>
</system.data>
Connection String Differences
MySqlConnector has some different default connection string options:
Option MySqlConnector Oracle’s Connector/NET NotesCharacterSet
, CharSet
Ignored; utf8mb4
is always used (server-defined) 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. ConnectionReset
Default is true
Default is false
MySqlConnector always resets pooled connections by default so that the connection is in a known state. This fixes MySQL Bug 77421. IgnoreCommandTransaction
Default is false
(not configurable, effective default is true
) See remarks under MySqlCommand below. IgnorePrepare
Default is false
true
for ≤ 8.0.22; false
for ≥ 8.0.23 This is a change if migrating from an older version of Connector/NET. LoadBalance
Default is RoundRobin
(not configurable, effective default is FailOver
) Connector/NET versions prior to v8.0.19 have a bug that prevents multiple host names being used. ServerRSAPublicKeyFile
(no default) (not configurable) Specify a file containing the server’s RSA public key to allow sha256_password
authentication over an insecure connection.
Connector/NET uses CertificateFile
to specify the client’s private key, unless SslCert
and SslKey
are specified, in which case it is used to specify the server’s CA certificate file; SslCa
is just an alias for this option. MySqlConnector always uses CertificateFile
for the client’s private key (in PFX format); SslCa
(aka CACertificateFile
) is a separate option to specify the server’s CA certificate.
Some connection string options that are supported in Connector/NET are not supported in MySqlConnector. For a full list of options that are supported in MySqlConnector, see the Connection Options.
AsyncConnector/NET implements the standard ADO.NET async methods, and adds some new ones (e.g., MySqlConnection.BeginTransactionAsync
, MySqlDataAdapter.FillAsync
) that don’t exist in ADO.NET. None of these methods have an asynchronous implementation, but all execute synchronously then return a completed Task
. This longstanding known bug was fixed in in Connector/NET v8.0.33.
Because the Connector/NET methods aren’t actually asynchronous, porting client code to MySqlConnector (which is asynchronous) can expose bugs that only occur when an async method completes asynchronously and resumes the await
-ing code on a background thread. To avoid deadlocks, make sure to never block on async code (e.g., with .Result
), use async all the way, use ConfigureAwait
correctly, and follow the best practices in async programming.
Prior to v8.3.0, Connector/NET allows MySqlDataReader.GetString()
to be called on many non-textual columns, and will implicitly convert the value to a string
(using the current locale). This is a frequent source of locale-dependent bugs, so MySqlConnector follows typical ADO.NET practice (e.g., SqlClient, npgsql) and disallows this (by throwing an InvalidCastException
).
To fix this, use the accessor method (e.g., GetInt32
, GetDouble
) that matches the column type, or perform an explicit conversion to string
by calling GetValue(x).ToString()
(optionally supplying the right CultureInfo
to use for formatting).
MySqlConnector adds full distributed transaction support (for client code using System.Transactions.Transaction
), while Connector/NET uses regular database transactions. As a result, code that uses TransactionScope
or MySqlConnection.EnlistTransaction
may execute differently with MySqlConnector. To get Connector/NET-compatible behavior, set UseXaTransactions=false
in your connection string.
Connector/NET allows a MySqlConnection
object to be reused after it has been disposed. MySqlConnector requires a new MySqlConnection
object to be created. See #331 for more details.
The return value of MySqlConnection.BeginTransactionAsync
has changed from Task<MySqlTransaction>
to ValueTask<MySqlTransaction>
to match the standard API in .NET Core 3.0. (This method does always perform I/O, so ValueTask
is not an optimization for MySqlConnector.)
All string
properties on MySqlConnectionStringBuilder
will return the empty string (instead of null
) if the property isn’t set.
Connector/NET allows a command to be executed even when MySqlCommand.Transaction
references a commited, rolled back, or disposed MySqlTransaction
. MySqlConnector will throw an InvalidOperationException
if the MySqlCommand.Transaction
property doesn’t reference the active transaction. This fixes MySQL Bug 88611. To disable this strict validation, set IgnoreCommandTransaction=true
in the connection string. See Transaction Usage for more details.
If MySqlCommand.CommandType
is CommandType.StoredProcedure
, the stored procedure name assigned to MySqlCommand.CommandText
must have any special characters escaped or quoted. Connector/NET will automatically quote some characters (such as spaces); MySqlConnector leaves this up to the developer.
Connector/NET provides MySqlDataAdapter.FillAsync
, FillSchemaAsync
, and UpdateAsync
methods, but these methods have a synchronous implementation. MySqlConnector only adds “Async” methods when they can be implemented asynchronously. This functionality depends on dotnet/runtime#22109 being implemented first. To migrate code, change it to call the synchronous methods instead.
The Connector/NET MySqlGeometry
type assumes that the geometry can only be a simple point. MySqlConnector removes most of the API that is based on those assumptions.
To avoid ambiguity, there are two different factory methods for constructing a MySqlGeometry
. Use the static factory method MySqlGeometry.FromMySql
(if you have a byte array containing MySQL’s internal format), or FromWkb
if you have Well-known Binary bytes.
The MySqlError[] MySqlInfoMessageEventArgs.errors
property has changed to IReadOnlyList<MySqlError> MySqlInfoMessageEventArgs.Errors
.
Connector/NET will automatically convert unknown MySqlParameter.Value
values to a string
by calling ToString()
, then convert that to bytes by calling Encoding.GetBytes()
using the packet’s encoding. This is error-prone and can introduce culture-sensitive conversions.
MySqlConnector requires all parameter values to be of a known, supported type. See MySqlParameter Types for details.
MySqlParameterCollectionConnector/NET will assign the names @Parameter1
, @Parameter2
, etc. to unnamed MySqlParameter
objects that are added to the MySqlCommand.Parameters
parameter collection. These generated names may be used in the SQL assigned to MySqlCommand.CommandText
. MySqlConnector requires all MySqlParameter
objects to be explicitly given a name, or used only as positional parameters if they’re unnamed.
For consistency with other ADO.NET providers, MySqlConnector will throw InvalidOperationException
(instead of MySqlException
) for various precondition checks that indicate misuse of the API (and not a problem related to MySQL Server).
The following bugs in Connector/NET are fixed by switching to MySqlConnector.
Open BugsMySqlCommand.Prepare
(Will never be supported)ColumnOrdinal
in schema table is 1-basedDateTimeOffset
ConnectionReset=True
does not preserve connection charsetMySqlCommand
can be executed even if it has “wrong” transactionMySqlConnection.Database
not updated after USE database;
MySqlCommandBuilder.DeriveParameters
fails for JSON
typeMySqlDateTime
valuesMySqlCommand.Prepare
BLOB
shifts it by four bytes when preparedMySqlDataReader.GetDateTime
and GetValue
return inconsistent valuesMySqlDataAdapter
throws timeout exception when an error occursMySqlException
loses data when serializedMySqlConnection.OpenAsync(CancellationToken)
doesn’t respect cancellation tokenMySqlDataReader.GetFieldValue<MySqlGeometry>
throws InvalidCastException
MySqlConnection.Open()
slow under load when using SSLrequire subject
KeepAlive
in connection string throws exception on .NET CoreStringBuilder
containing non-BMP characters as MySqlParameter.Value
MySqlParameterCollection.Add(object)
has quadratic performanceMySqlConnectionStringBuilder.ContainsKey
method gives wrong resultSystem.ArgumentException
TransactionScope.Dispose
throws “Connection must be valid and open to rollback”ExecuteReaderAsync
hangs instead of cancelling query after CommandTimeout
OpenAsync(CancellationToken)
doesn’t throw for cancelled tokenBIT(n)
parameter size incorrectly returns 0SET NAMES
using an unsupported valueMySqlDataReader.GetX
performs culture-sensitive conversionsMySqlPool.ClearAsync
is not thread-safeMySqlConnection.OpenAsync
throws exception when UseCompression = true
NullReferenceException
thrown when using prepared statement under OpenTelemetryExecuteNonQueryAsync
hangs with DDL if UseCompression=True
These bugs are fixed in the latest version of MySQL Connector/NET, but were fixed first in MySqlConnector.
Async
methods execute synchronously (fixed in v8.0.33)TIME(3)
and TIME(6)
fields serialize milliseconds incorrectlyStream
to bulk load dataTINYINT(1)
values start being returned as sbyte
after NULL
Server
connection string option may now contain multiple, comma separated hosts that will be tried in order until a connection succeeds.
in its nameColumnSize
in schema table is incorrect for CHAR(36)
and BLOB
columnsIsLong
is schema table is incorrect for LONGTEXT
and LONGBLOB
columnsdecimal(n, 0)
has wrong NumericPrecision
TINYINT(1)
is not returned as bool
if MySqlCommand.Prepare
is calledMySqlClientFactory.Instance.CreateDataAdapter()
and CreateCommandBuilder
return null
MySqlDataReader
cannot outlive MySqlCommand
ReservedWords
schema contains incorrect dataMySqlDataReader
is closed by an unrelated command disposalYEAR
column retrieved incorrectly with prepared command00:00:00
is converted to NULL
with prepared commandTIME(n)
column loses microseconds with prepared commandMySqlException
thrown from TransactionScope.Dispose
MySqlParameter.Clone
doesn’t copy all property valuesMySqlDbType.LongText
values encoded incorrectly with prepared statementsFormatException
thrown when connecting to MySQL Server 8.0.13SHOW VARIABLES
when connection is madeMySqlParameterCollection.Add
precondition check isn’t consistentMySqlDataReader.GetStream
throws IndexOutOfRangeException
MySqlCommand.Cancel
throws exceptionMySqlDbType.JSON
MySqlDbType.Int24
Could not load file or assembly 'Renci.SshNet'
when opening connectionWHERE
clause using MySqlGeometry
as parameter finds no rowsMySqlException
when inserting a MySqlGeometry
valueMySqlCommand.LastInsertedId
returns 0 after executing multiple statementsGetSchemaTable()
returns table for stored procedure with output parametersMySqlConnection.Clone
discloses connection passwordnew MySqlConnection(null)
throws NullReferenceException
TINYINT(1)
columnGetSchema("Procedures")
returns ROUTINE_DEFINITION
of "System.Byte[]"
TIME(n)
microsecond values deserialized incorrectly with prepared commandCommand.Prepare
sends wrong statement to serverMySqlCommand.Parameters.Insert(-1)
succeeds but should failCHAR(36)
column containing NULL
MySqlParameter.Value
changed from null to 0
BOOL
parameter can only be mapped to MySqlDbType.Byte
JSON
parameter throws “Unhandled type encountered” MySqlException
MySqlCommand.Cancel
throws NullReferenceException
for a closed connectionMemoryStream
as MySqlParameter.Value
CHAR(36)
column if MySqlCommand
is preparedTimeSpan
parameters lose microseconds with prepared statementMySqlConnectionStringBuilder.TryGetValue
always returns false
MySqlCommand.Clone
doesn’t clone attributesMySqlCommandBuilder
doesn’t support tables with BIGINT UNSIGNED
primary keyMySqlConnection.Open
throws AggregateException
instead of MySqlException
CancellationToken
doesn’t cancel MySqlConnection.OpenAsync
MySqlDataReader.GetFieldValue<Stream>
throws InvalidCastException
MySqlDbType.Enum
or MySqlDbType.Set
with prepared commandMySqlDbType.Int24
MySqlParameter.Clone
loses specific MySqlDbType
.MySqlCommand.LastInsertedId
is incorrect if multiple rows are inserted.OpenAsync
throws unhandled exception from thread poolMinPoolSize
configuration is not honoredRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4