我试图创建一个类来保存我所有的数据库操作。我想在每次调用这个类时启动一个MySQL连接,执行它需要做的任何db操作,并在完成后关闭它。在
到目前为止,我得到的是:import MySQLdb
class Database_Test(object):
def __init__(self, db_local):
self.db_conn = MySQLdb.connect(**db_local)
self.db_cursor = self.db_conn.cursor()
def get_row(self, sql, data = None):
self.db_cursor.execute(sql)
self.resultset = self.db_cursor.fetchall()
self.db_cursor.close()
return self.resultset
# Close db connection something like this?
# db_conn.close()
db_config = {
'host':"127.0.0.1", # database host
'port': 3306, # port
'user':"root", # username
'passwd':"admin", # password
'db':"test", # database
'charset':'utf8' # charset encoding
}
sql = "SELECT * FROM mytest LIMIT 10"
test = Database_Test(db_config)
test.get_row(sql)
print(test)
我得到的是:
^{pr2}$
不知怎么的,这不是我期望得到的,因为我希望从数据库中得到一些记录。在