Search code examples
pythonsqldatatableplotly-dash

Generate plotly DataTable from SQL query


I'm quite a new to dash and python, I am currently trying to have a callback for 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

Here what I have implemented so far;


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)

Solution

  • You've set up the Output to pass to the data prop, so your return value should simply be the data variable, like this:

    return data

    By putting it into a dictionary, Dash is looking for a data prop of the data prop, which does not exist, and that's why you get the error that data is not defined.