简体   繁体   English

关闭游标并与Python和MySQLdb连接

[英]Closing cursor and connection with Python and MySQLdb

I have a simple web.py-based app that uses MySQLdb. 我有一个简单的基于web.py的应用程序,它使用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() . 我将类实例化为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. 用于连接的db.close()和用于游标的cur.close()

http://mysql-python.sourceforge.net/MySQLdb.html 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. 一旦变量被销毁,Python就会关闭游标,所以当你的类的实例不再存在时 - 游标将被关闭。

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. 首先为类名和变量使用不同的名称,因为您对类名和连接使用了相同的名称('db')。

Next, you need to define conn (in your question db line no 3) as self.conn . 接下来,您需要将conn(在您的问题db第3行)定义为self.conn

import MySQLdb 导入MySQLdb

class db(): 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. 注意:如果在类bleh中有多个函数从数据库获取数据,请确保在函数中关闭游标和连接,这在最后调用。 Or you may have a seperate function, which closes cursor and connection. 或者你可能有一个单独的功能,它关闭光标和连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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