Is it a good idea to open a single MySQL connection (from C#) and then use that same connection to perform multiple SQL statements? Or should I open and close a separate MySQL connection for each statement I need to execute?
Is something like this (the pseudo-code below) possible, or should I avoid the pattern of running multiple SQL statements using the same connection?
MYSQL.OPEN()
FOR(INT I =0 ; I < CODE.COUNT ; I ++)
{
ALL ITEMS I WANT ENTER BY ONCE TIME OPEN CONNECTION ( is it possible) or wrong idea ?
}
MYSQL.CLOSE()
Don’t churn connections.
Open the connection to the MySQL database, do all the work you need to do, then close the connection.
Opening and closing a connection for each SQL statement is a LOT of heavy lifting for the database server to do. (It looks simple from the client side, but the server has a code path that is pretty significant.)
A connection pool is a commonly implemented approach. A connection pool manages a set of connections to the database; clients can “borrow” connections from the pool, so churning (lots of requests for connections) is handled by the pool, at the client side, and the database server sees a steady set of connections. so everyone is happy.