Pages: 1
Author Topic: MySQL - constant connection  (25,927 Views)
Offline (Unknown gender) kkg

Member
Joined: Nov 2009
Posts: 84
View profile
Posted on: June 01, 2011, 05:27:02 PM
Just a quick question regarding having a server that extracts user information from / writes information to a database.
Should I practice:
1) Opening a connection when the server starts, close the connection when the server closes
2) Open a connection only when the database needs to be used (possibly frequently) and close it immediately

I'm not really aware of the raw behind a connection with a SQL database, so I'm not sure of the security consequences etc etc
I would assume 1) is a lot faster also.

Note: If you are offering a suggestion, could you offer it for two different situations: where the database is local to the server and where the database is hosted online?

Thanks yy0y0y0 xoxoxo
Offline (Unknown gender) IsmAvatar

LateralGM Developer
LGM Developer
Joined: Apr 2008
Posts: 877
View profile
Reply #1 Posted on: June 01, 2011, 08:18:22 PM
It's not unusual for a language that interfaces with MySQL to reuse existing connections when you attempt to connect.
In php, calling mysql_connect() with the same information twice will return the same handle.

It is worth noting, however, that keeping a connection open for too long without querying will cause the connection to timeout. This is usually default of about 8 hours.

Generally, you should open a connection whenever an instance starts needing to access the database. I say instance, because you could have two instances running and they'd need to access the server simultaneously. It's inadvisable to try this multi-instance approach with only 1 super-global connection.

Beyond that, I'm not sure of the overhead of opening and closing a connection. You might want to ask on a mysql forum or forum of the language of your choice.
Offline (Unknown gender) RetroX

Master of all things Linux
Contributor
Joined: Apr 2008
Posts: 1,055
View profile
Reply #2 Posted on: June 02, 2011, 01:32:10 AM
The usual approach is to open it and store the handle, then use that:
$conn = mysql_connect($server, $user, $pass);
mysql_query($query, $conn);
mysql_close($conn);
Pages: 1