import pymysql class DBHandler(): """数据库操作""" def __init__(self, host='', port= , username='', password='', db_name='f' ): # 得到一个连接对象 self.connection = pymysql.connect(host=host, port=port, user=username, password=password, database=db_name) def query_one(self, sql): """查询一条记录""" # 得到游标 cursor = self.connection.cursor() # 提交,同步最新的数据库信息 self.connection.commit() # 执行 cursor.execute(sql) # 得到执行结果 data = cursor.fetchone() # 关闭游标 cursor.close() return data def query_all(self, sql): """查询所有的记录""" cursor = self.connection.cursor() # 提交 self.connection.commit() cursor.execute(sql) data = cursor.fetchall() cursor.close() return data def close(self): self.connection.close() # 判断是否是主程序运行,如果不是主程序运行,就不执行下面的代码,方便debug if __name__ == '__main__': # 简单的测试代码。 db = DBHandler() ret = db.query_one('select reg_name, id from member limit 5;') print(ret) db.close()