人生苦短,早用Python!
相信大家都用过Navicat,Sqlyog,癞蛤蟆之类的数据库可视化工具。那么,自己能不能做一个类似的数据库可视化的东西呢,毕竟原生的命令行不是很美观,Python50行代码搞定!
文章目录先上效果图:
- 0.导入相关依赖库
- 1.编写数据库配置信息
- 2.创建Dash对象
- 3.设置页面布局
- 4.编写回调函数
- 5.启动
- 6.效果
- 7.想法
缺少相关模块,自行下载即可,下载命令: pip install xxx
import dash import dash_html_components as html import dash_bootstrap_components as dbc import dash_core_components as dcc from dash.dependencies import Input, Output, State import pandas as pd from sqlalchemy import create_engine1.编写数据库配置信息
以关系型数据库Postgresql数据库为例,当然也可以使用其他数据库!
postgres_url = 'postgresql://postgres:root@localhost:5432/db1' engine = create_engine(postgres_url)2.创建Dash对象
app = dash.Dash(__name__)3.设置页面布局
页面布局使用了bootstrap的网格布局,两行,第一行:两个按钮,一个下拉框,第二行:留白部分,显示查询的表信息!
app.layout = html.Div(
dbc.Container([
dbc.Row([
dbc.Col(dbc.Button(
'刷新数据库信息', id='refresh', style={'width': '100%'}),
width=2),
dbc.Col(dcc.Dropdown(
id='db_tables', placeholder='请选择一张表', style={'width': '100%'}),
width=4),
dbc.Col(dbc.Button('查询', id='query', style={'width': '100%'}),
width=1)
]),
html.Br(),
dbc.Row([dbc.Col(id='query_result')])
],
style={'margin-top': '50px'}))
4.编写回调函数
两个交互的回调函数,第一个:点击按钮,把表名传递给下拉框;第二个:把下拉框中选择的值,传递给要查询的SQL语句,点击按钮查询!
@app.callback(Output('db_tables', 'options'),
Input('refresh', 'n_clicks'),
prevent_initial_call=True)
def query_data(n_clicks):
tables = pd.read_sql_query(
"select tablename from pg_tables where schemaname='public'",
con=engine)
return [{'label': name, 'value': name} for name in tables['tablename']]
@app.callback(Output('query_result', 'children'),
Input('query', 'n_clicks'),
State('db_tables', 'value'),
prevent_initial_call=True)
def query_table(n_clicks, value):
if value:
resultDF = pd.read_sql_query(f'select * from {value}', con=engine)
return html.Div(dbc.Table.from_dataframe(resultDF, striped=True),
style={
'height': '600px',
'overflow': 'auto'
})
else:
return dash.no_update
5.启动
if __name__ == '__main__':
app.run_server(debug=True)
6.效果
7.想法
如果想扩展,可以前面加一个数据的下拉框,就可以查询到不同库下面的表;如果想更换数据库,比如换成MySQL,只需要把第一步的数据库信息做下变更,还有查询库下所有标的sql需要变更,“show tables”!
觉得还行的,可以点赞收藏一波,Byebye!



