0

Does python (version 2.7, 3.3) close the database connection immediately after a program is finished?

For example:

import MySQLdb
conn = sqlite3.connect(host="localost", user="adam", password="12345", db ="my_db")

c = conn.cursor()

c.execute('''SELECT * FROM MY_TABLE''')

cur.close() # Do I really need that ?

conn.close() # Do I really need that ?

Could there be an issue with closing connections, if I run this script again and again immediately one after another?

ps. Yes, I know that the best practice is to close all the resources.

2 Answers 2

2

As you mentioned you should close the connection explicitly in your code. Most of the time letting the connection implicitly close will not cause issues, but with some DBMSes weird things could happen.

SQLite will rollback any open transactions for example.

Also i read somewhere you can use the withstatement when you are using MYSQL might be worth googling.

Sign up to request clarification or add additional context in comments.

Comments

1

You have a bit confusion in your code snippet, mixing mysql and sqlite3 it seems.

I guessed you meant mysql all the way, and rewrote your code to:

import MySQLdb
conn = MySQLdb.connect(host="127.0.0.1", user="test", passwd="", db="test")
c = conn.cursor()
c.execute('''SELECT now()''')

Then I checked connection state, both using netstat and mysql processlist, and on my linux it seems that when the scripts ends, connection is closed, leaving the tcp connection in TIME_WAIT as expected.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.