要求:使用 pymysql 连接数据库,查询某一指定数据库中的所有数据表
代码实现:
import pymysql
def get_tables_from_db():
tables = []
config = {
'host': '主机地址',
'port': 3306,
'user': 'mysql用户名',
'password': '密码',
}
con = pymysql.connect(**config)
cursor = con.cursor()
sql = 'select TABLE_NAME, table_type, engine from information_schema.tables where table_schema="指定的数据库名"'
try:
cursor.execute(sql)
results = cursor.fetchall()
print(len(results))
print("table_name", "table_type", "engine")
for row in results:
name = row[0]
type = row[1]
engine = row[2]
tables.append(name)
print(name, type, engine)
except Exception as e:
raise e
finally:
con.close()
return tables
tables = get_tables_from_db()