Python MySQLdb-类中的连接
我正在做一个Python项目,在这个项目中,我必须从数据库中查找和检索数据。Python MySQLdb-类中的连接,python,python-3.x,mysql-python,Python,Python 3.x,Mysql Python,我正在做一个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,s
我试着创建一个类,在这个类中我声明了连接并进行了查询,这里是我迄今为止所拥有的更多内容
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';"))
因此,主要问题是变量
db
和cursor
不能从同一类的其他def/函数调用。我想得到的是一个完善的查询,在这里我可以进行查询并检索它的内容。这将总结我的代码,因此我应该这样做。这不是用Python编写类的方式。您需要在方法中定义连接和光标,并通过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
我通常使用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.close()
@property
def connection(self):
return self._conn
@property
def cursor(self):
return self._cursor
def commit(self):
self.connection.commit()
def close(self, commit=True):
if commit:
self.commit()
self.connection.close()
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()
这将允许您使用数据库
类,通常类似于db=Database('db_file.sqlite)
,或者在带有语句的中:
with Database('db_file.sqlite') as db:
# do stuff
当with
语句退出时,连接将自动提交并关闭
然后,您可以封装在方法中经常执行的特定查询,并使它们易于访问。例如,如果您正在处理交易记录,您可以使用一种方法按日期获取它们:
def transactions_by_date(self, date):
sql = "SELECT * FROM transactions WHERE transaction_date = ?"
return self.query(sql, (date,))
下面是一些示例代码,我们在其中创建一个表,添加一些数据,然后将其读回:
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)
我希望这有帮助 您可以使用构造函数进行连接。创建类的对象时,构造函数将自动调用
import MySQLdb
class Connection:
def __init__(self):
self.con=MySQLdb.connect("127.0.0.1","root","","db_name",3306)
self.cmd=self.con.cursor()
obj=Connection()
示例配置类(CONFIG.py):
想想这句话<代码>sql.cursor.execute(sql)
。。。哪个sql
变量将用于获取光标?参数,而不是类。您应该从问题中删除不必要的标记。它要么是python 2.7,要么是python 3,要么与某个版本无关。@cricket_007提交的版本,因为它是一个函数,这对我帮助很大!谢谢,我没有意识到我可以将它们添加到\uuuuu init\uuuuuuu
中,您如何称呼这些类?比如:print(sql.query(“select*fromtest”)
@Daniel Roseman感谢您提供了这个解决方案,我们需要担心关闭连接/光标吗?答案太棒了!非常感谢,我不理解\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
语句,当你中使用该类时,返回该类的实例化版本,DBase()作为db:
上下文?若否,原因为何?谢谢至少在pyscopg2
中(用于Python的postgres客户端),当您关闭连接时,光标将自动关闭,因此我不必显式地执行此操作。这很可能会为您解决。欢迎使用SO.:)这与现有答案有何不同,甚至更好?
from config import Config
import MySQLdb
class Connection:
def __init__(self):
self.db=MySQLdb.connect(
Config.DATABASE_CONFIG['server'],
Config.DATABASE_CONFIG['user'],
Config.DATABASE_CONFIG['password'],
Config.DATABASE_CONFIG['name']
)
self.db.autocommit(True)
self.db.set_character_set('utf8mb4')
self.cur=self.db.cursor()
class Config(object):
DATABASE_CONFIG = {
'server': 'localhost',
'user': 'dbuser',
'password': 'password',
'name': 'dbname',
}