Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 190535
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T16:15:52+00:00 2026-05-11T16:15:52+00:00

The function code: # Connect to the DB try: dbi = MySQLdb.connect(host=’localhost’, \ user=’user’,

  • 0

The function code:

# Connect to the DB
try:
    dbi = MySQLdb.connect(host='localhost', \
                          user='user', \
                          passwd='pass', \
                          db='dbname', \
                          port=3309)

    print "Connected to DB ..."

except MySQLdb.Error, e:
    apiErr = 2
    apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
    return

    # To prevent try..finally bug in python2.4,
    # one has to nest the "try: except:" part. 
try:
    try:
        sql = dbi.cursor()
        sql.execute("""
        SELECT *
        FROM table
        WHERE idClient =  %s
        """, (key, ))

        access = sql.fetchall()

        # [some more code here]           

    except MySQLdb.Error, e:
        apiErr = 2
        apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
        return

finally:
    sql.close()
    dbi.close()

I understand that in a try .. except .. finally, the finally block will always execute.
In the above code, I don’t want the finally in the second try block to execute if there is an exception in the first try block. What am I doing wrong?

(Note: Using python 2.4)

Clarification: I am not aware if MySQLdb closes connections automatically when an error occurs. The problem I am facing with the above code is, when there is an error in establishing a connection (the first try block of the code), calling dbi.close() in the finally block raises “AttributeError: ‘NoneType’ object has no attribute ‘close'” with reference to dbi …

Solution:
This worked as desired –

# define at the start 
dbi = None
sql = None

In the finally block,

if sql is not None:
    sql.close()
if dbi is not None:
    dbi.close()

Thanks to those who replied. I learned something new from all of you. (I’ll try to phrase my questions more clearly the next time :).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T16:15:52+00:00Added an answer on May 11, 2026 at 4:15 pm

    I think in this case you do want to use finally, because you want to close those connections.

    I disagree with the notion that you should have two try blocks in the same method.

    I think the flaw in the design is acquiring the connection and performing the query in the same method. I would recommend separating the two. A service class or method knows about the unit of work. It should acquire the connection, pass it to another class that performs the query, and closes the connection when it’s done. That way the query method can throw any exception it encounters and leave the cleanup to the class or method that’s responsible for the connection.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 123k
  • Answers 123k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Your problem is that when you do: <xsl:call-template name="kreator" />… May 12, 2026 at 1:08 am
  • Editorial Team
    Editorial Team added an answer You can ask Git to ignore given untracked files using… May 12, 2026 at 1:08 am
  • Editorial Team
    Editorial Team added an answer First you can fill a DataTable with the results: DataTable… May 12, 2026 at 1:08 am

Related Questions

The function code: # Connect to the DB try: dbi = MySQLdb.connect(host='localhost', \ user='user',
Hey guys, I have a problem (again). This time I am trying to use
I am using DBExpress in Delphi 2007 to connect to a MySQL5 database server
I'm trying to access a large Oracle database through SQL Server using OPENROWSET in
I have an API that is dependent on certain state information between requests. As

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.