This question is similar to this one: Using MySql.Data with C# while not making a MySqlConnection
Basically, I can see in the documentation: https://dev.mysql.com/doc/connector-net/en/connector-net-connections-pooling.html it says to avoid creating a MySqlConnection object, however, it doesn’t say how to handle transactions.
Is there a similar api that is supposed to be used instead of creating a MySqlConnection object as detailed here? https://dev.mysql.com/doc/dev/connector-net/latest/api/data_api/MySql.Data.MySqlClient.MySqlTransaction.html
6
The documentation doesn’t say to “avoid creating a MySqlConnection object” as a blanket rule.
It says:
- “Do not create a globally accessible instance of
MySqlConnection
and then manually open and close it.” This is good advice. - “One approach that simplifies things is to avoid creating a MySqlConnection object manually. Instead, use the overloaded methods that take a connection string as an argument.” This is a recommendation for a possible approach you can use when a special-purpose API has a method that takes a connection string and does its work.
However, you don’t have to do that, and there’s nothing wrong with new MySqlConnection(connectionString)
.
The other documentation you linked to (here) shows a perfectly acceptable way of opening a connection and starting a transaction:
using MySqlConnection myConnection = new MySqlConnection(myConnString);
myConnection.Open();
// Start a local transaction
using MySqlTransaction myTrans = myConnection.BeginTransaction();
using MySqlCommand myCommand = myConnection.CreateCommand();
// do your work here...
myTrans.Commit();