问题
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