Python MySQLdb - 类中的连接

Mar*_*orà 11 python mysql-python python-3.x

我正在制作一个Python项目,我必须从数据库中搜索和检索数据.
我尝试创建一个类,在其中我声明了连接并进行了查询,这里到目前为止我没有更多.

import MySQLdb
dbc =("localhost","root","1234","users")
class sql:
    db = MySQLdb.connect(dbc[0],dbc[1],dbc[2],dbc[3])
    cursor = db.cursor()

    def query(self,sql):
        sql.cursor.execute(sql)
        return sql.cursor.fetchone()

    def rows(self):
        return sql.cursor.rowcount

sqlI = sql()
print(sqlI.query("SELECT `current_points` FROM `users` WHERE `nick` = 'username';"))
Run Code Online (Sandbox Code Playgroud)

因此,主要问题是变量db并且cursor不能从同一个类的其他def /函数调用.我想得到的是一个很好的查询,我可以在那里查询并检索它的内容.这将总结我的代码,因此我应该这样做.

car*_*t42 27

我通常使用psycopg2/postgres,但这是我经常使用的基本DB类,以Python的SQLite为例:

import sqlite3

class Database:
    def __init__(self, name):
        self._conn = sqlite3.connect(name)
        self._cursor = self._conn.cursor()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.commit()
        self.connection.close()

    @property
    def connection(self):
        return self._conn

    @property
    def cursor(self):
        return self._cursor

    def commit(self):
        self.connection.commit()

    def execute(self, sql, params=None):
        self.cursor.execute(sql, params or ())

    def fetchall(self):
        return self.cursor.fetchall()

    def fetchone(self):
        return self.cursor.fetchone()

    def query(self, sql, params=None):
        self.cursor.execute(sql, params or ())
        return self.fetchall()
Run Code Online (Sandbox Code Playgroud)

这将允许您Database通常喜欢db = Database('db_file.sqlite)或在with语句中使用该类:

with Database('db_file.sqlite') as db:
    # do stuff
Run Code Online (Sandbox Code Playgroud)

并且with语句退出时连接将自动提交和关闭.

然后,您可以封装在方法中经常执行的特定查询,并使它们易于访问.例如,如果您正在处理事务记录,则可以使用一种方法按日期获取它们:

def transactions_by_date(self, date):
    sql = "SELECT * FROM transactions WHERE transaction_date = ?"
    return self.query(sql, (date,))
Run Code Online (Sandbox Code Playgroud)

下面是一些示例代码,我们创建一个表,添加一些数据,然后将其读回:

with Database('my_db.sqlite') as db:
    db.execute('CREATE TABLE comments(pkey INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR, comment_body VARCHAR, date_posted TIMESTAMP)')
    db.execute('INSERT INTO comments (username, comment_body, date_posted) VALUES (?, ?, current_date)', ('tom', 'this is a comment'))
    comments = db.query('SELECT * FROM comments')
    print(comments)
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!

  • `__enter__`和`__exit__`“魔术方法”让类使用`with`语句。基本上是说,当在带有DBase()as db:的上下文中使用该类时,返回该类的实例化版本。 (2认同)

Dan*_*man 13

那不是你用Python编写类的方式.您需要在__init__方法内定义连接和光标,并通过它们引用它们self.

class sql:

    dbc = ("localhost","root","1234","users")

    def __init__(self):
        db = MySQLdb.connect(*self.dbc)
        self.cursor = db.cursor()

    def query(self,sql):
        self.cursor.execute(sql)
        return self.cursor.fetchone()

    def rows(self):
        return self.cursor.rowcount
Run Code Online (Sandbox Code Playgroud)