简体   繁体   中英

Closing cursor and connection with Python and MySQLdb

I have a simple web.py-based app that uses MySQLdb. I have a class that handles database operations like so:

class db():
   def __init__(self):
       db = MySQLdb.connect(host='mysql.server', user='user', passwd='pass', db='app')
       self.cur = db.cursor()

   def get_data(self):
       sql = "SELECT * FROM foobar"
       self.cur.execute(sql)
       rs = self.cur
       r.fetchall()
       return rs

I instantiate the class like so DB = db() . Then, in another class, I will refer to it.

class bleh()
   def blarg():
      DB.get_data()

With something like this, where would I close the cursor and connection? Or am I approaching this completely wrong?

db.close() for connection and cur.close() for cursor.

http://mysql-python.sourceforge.net/MySQLdb.html

EDIT:

But if it give it a bit thought - you won't need to close cursor. Python closes the cursor once the variable is destroyed, so when the instance of your class does not exist anymore -- cursor will be closed.

First of all use different names for class-name and variable as you have used same name ('db') for class-name and connection as well.

Next, you need to define conn (in your question db line no 3) as self.conn .

import MySQLdb

class db():

 def __init__(self): self.conn = MySQLdb.connect(host='mysql.server', user='user', passwd='pass', db='app') self.cur = self.conn.cursor() def get_data(self): sql = "SELECT * FROM test" self.cur.execute(sql) rs = self.cur rs.fetchall() return rs 
class bleh()
    def blarg():
        data = DB.get_data()
        DB.cur.close()
        DB.conn.close()

Note: If you have multiple functions in class bleh to get data from database make sure that you close cursor and connection in function, which is to called in last. Or you may have a seperate function, which closes cursor and connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM