Results 1 to 4 of 4

Thread: Best placement for connection strings - MySQL on Linux/Apache

  1. #1
    Join Date
    Apr 2008

    Best placement for connection strings - MySQL on Linux/Apache

    Question: is it better to surround a query string and related processing with open and close connections strings, or is it best to open the connection at the beginning of a lengthy script and close it at the end of the script? I ask this in terms of coding efficiency, resource utilization of the server and any potential security risks. Thanks.

  2. #2
    Join Date
    Nov 2008
    If you will be doing multiple queries within the same script / within a short period of time, the best thing to do is open the connection at the beginning, and close it at the end.

    There are two reasons for this: Connections are expensive. There is tremendous overhead (compared to running queries) with setting up the connection, opening it, etc. This will slow down your script's execution considerably. Second, it reduces the amount of work on the database side.

    If, on the other hand, you're just doing a single query and then a bunch of processing based on that, it doesn't hurt to close the connection right away (assuming you've gotten all your data), to free up the connection for other resources.


  3. #3
    Join Date
    Apr 2008
    Excellent. Thanks for the advice.

  4. #4
    Join Date
    Aug 2004
    I'm not sure about the overhead being "tremendous", but I guess that's platform- and configuration-dependent, along with how many milliseconds you consider to be "tremendous." That being said, there is an overhead, so I agree that in the vast majority of cases I would opt for one connection at the start and not closing until I'm done with DB access.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center