Generate plotly DataTable from SQL query

纵饮孤独 提交于 2020-02-25 05:30:30

问题


i quite new to dash and python, i am currently trying to have a callback for my datatable which retrieves from the SQL on my computer. However, i am not able to do so. Any idea why? I got this error: columns = [{'num': i, 'id': i} for i in data.columns],data=[] NameError: name 'data' is not defined

import pandas as pd
import dash
import dash_table
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
from random import random
import plotly
import pyodbc
global data
def connectSQLServer(driver, server, db):
    connSQLServer = pyodbc.connect(
        r'DRIVER={' + driver + '};'
        r'SERVER=' + server + ';'
        r'DATABASE=' + db + ';'
        r'Trusted_Connection=yes;',
        autocommit=True
    )
    return connSQLServer


app = dash.Dash()

app.layout = html.Div([dash_table.DataTable(id='raw_data',

                                            columns = [{'num': i, 'id': i} for i in data.columns],data=[]
                                            #data = data.to_dict('records')
                                            ),
                       dcc.Interval(id='interval_component',
                                    interval=1000,
                                    n_intervals=0
                                    )
                       ])


@app.callback(Output('raw_data', 'data'), [Input('interval_component', 'n_intervals')])
def update_table(n_intervals):

    dataSQL = []  # set an empty list
    global data
    sql_conn = connectSQLServer(
        'ODBC Driver 13 for SQL Server', 'DESKTOP\SQL', 'display')
    cursor = sql_conn.cursor()
    cursor.execute("SELECT num,ID FROM dbo.stats")
    rows = cursor.fetchall()
    for row in rows:
        dataSQL.append(list(row))
        labels = ['num', 'id']
        data = pd.DataFrame.from_records(dataSQL, columns=labels)
        data = data.to_dict('records')
        return {'data': [data]}


if __name__ == '__main__':
    app.run_server(port=5000, debug=True)

来源:https://stackoverflow.com/questions/60356343/generate-plotly-datatable-from-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!