0

I want to write a function for mysql connection to use it any where. there is tow way in my mind

1)in top of function open connection and execute query and close connection. in this way each query open connection and close it but have easy usage because no need to handle open and close connection in separate function and call them in top and bottom of code

2)write a function for opening connection and another function for closing it and call them in top an bottom of code. in this way one connection open and use for multiple query then close

my question is:

is there any difference to open and close the db connection multiple times or it doesn't matter? which way have a better performance(in second way connection may open some minutes)?

I use some programming language like java, php and ... .but my question is general

sadegh
  • 43
  • 3
  • 12

2 Answers2

2

Each time you open and close a connection you are using resources. Imagine you have 100 requests per second. Each time you perform 2 operations. Open and close a connection. The response time increase.

Is better to use pool Connections. So, you have 5 open connections waiting for querys. When the connection is not in use, the connection returns to the pool and wait for another request.

Or you can try a persist connection. Both have pros and cons.

But never, never ever open and close connections for each request. Look this response

MySQL - Persistent connection vs connection pooling

Community
  • 1
  • 1
manuerumx
  • 1,230
  • 14
  • 28
0

i think there will be not so much difference but it will be better if you close your connection frequently so mysql connection limit will not be increase and if you keep connection open, So there will be chances to cross your connection limit.

Ashish Tiwari
  • 1,919
  • 1
  • 14
  • 26