# 引入 pymysql import pymysql as mysql def main(): # 连接数据库 db = mysql.connect(host='localhost', user='root', password='', db='test', charset='utf8') # 创建游标对象 cursor = db.cursor() # sql 语句 sql = 'SELECT a.*, c.dep_name AS father_dep, b.dep_name FROM person AS a LEFT JOIN department AS b on a.person_department = b.dep_id LEFT JOIN department AS c on b.dep_father_id = c.dep_id' try: # 执行 sql 语句 cursor.execute(sql) # 将查询语句提交至数据库 db.commit() except: # 发生错误时回滚 db.rollback() else: # 没发生错误 就输出内容 print(cursor.fetchall()) finally: # 最后,不管是否发生错误都关闭一下数据库连接 db.close() if __name__ == '__main__': main()
运行后的内容
((1, '测试一号', 2, '男', '总部', '部门一'), (2, '测试二号', 3, '女', '部门一', '部门二'))