在MySQLdb(python)

时间:2017-05-22 04:43:42

标签: python mysql-python

下面这段代码运行得很好,但是我想把这段代码分成函数(这是我第一次使用MySQLdb),

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","user_name","pass","db_name" )

cursor = db.cursor()
sql = "SELECT activity_log.datetime FROM activity_log"
cursor.execute(sql)
date_data = cursor.fetchall()
for content in date_data:
    print content   

# disconnect from server
db.close()

问题:如何创建一个数据库连接并将其用于多个函数,这是我到目前为止所写的(不起作用):

import MySQLdb

class DB():
    def __init__(self): 
        db = MySQLdb.connect("locahost", "user_name", "pass", "db_name")
        self.cur = db.cursor()

    def time_statistic(self):
        sql = "SELECT activity_log.datetime FROM activity_log"
        self.cur.execute(sql)
        self.date_data = self.cursor.fetchone()
        for content in self.date_data:
            print content 

    def test1(self):
        pass

if __name__ == '__main__':

    db = DB.connect("db_name" )
    db.time_statistic(self)
    db.test1(self)
    db.close()

1 个答案:

答案 0 :(得分:0)

您需要将参数传递给 init ,以确保该类连接到正确的数据库。

import MySQLdb

class DB():
    def __init__(self, server, user, password, db_name): 
        db = MySQLdb.connect(server, user, password, db_name)
        self.cur = db.cursor()

    def time_statistic(self):
        sql = "SELECT activity_log.datetime FROM activity_log"
        self.cur.execute(sql)
        self.date_data = self.cursor.fetchone()
        for content in self.date_data:
            print content 

    def test1(self):
        pass


if __name__ == '__main__':

    db = DB(<server>, <user>, <password>, <db_name>)
    db.time_statistic()
    db.test1()

替换&lt;&gt;中的参数使用实际值,您需要连接到数据库。您可能还想在上面的代码中添加一些错误处理。