通过回调用新行更新破折号数据表

时间:2020-03-13 11:16:45

标签: python sql plotly-dash

我希望从回调中使用的sql查询中获得一个更新的破折表,它将每隔几秒钟更新一次。但是,获取新行时出错。 现在被打了一段时间 你能帮忙的话,我会很高兴 错误: 回调错误更新raw_data.data

代码:

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
import plotly
import pyodbc

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

sql_conn = connectSQLServer(
    'ODBC Driver 13 for SQL Server', 'DESKTOP\SQLEXPRESS', 'display')
cursor = sql_conn.cursor()
d = {'x': [], 'y': [], 'z': [], 'a': []}
sql = 'select * from dbo.data2'
cursor.execute(sql)
myresult = cursor.fetchall()
# d = { 'x': [], 'y': [] }
for x in myresult:
    d['x'].append(x[0])
    d['y'].append(x[1])
    d['z'].append(x[2])
    d['a'].append(x[3])
df = pd.DataFrame(d)

app = dash.Dash(__name__)
app.layout = html.Div([dash_table.DataTable(id='raw_data',

                                            columns = [{'name': i, 'id': i} for i in df.columns],
                                            data = df.to_dict("rows"),
                                            ),
                       dcc.Interval(id='interval_component',
                                    interval=1000,
                                    n_intervals=0
                                    )
                       ])
d = {'x': [], 'y': [], 'z': [], 'a': []}

@app.callback(Output('raw_data', 'data'), [Input('interval_component', 'n_intervals')])
def update_table(n_intervals):
    sql_conn = connectSQLServer(
        'ODBC Driver 13 for SQL Server', 'DESKTOP\SQL', 'display')
    cursor = sql_conn.cursor()
    cursor.execute("SELECT * FROM dbo.data2")
    rows = cursor.fetchall()
    for x in rows:
        d['x'].append(x[0])
        d['y'].append(x[1])
        d['z'].append(x[2])
        d['a'].append(x[3])
    df = pd.Dataframe(d)
    return df
if __name__ == '__main__':
    app.run_server(port=7000, debug=True)

1 个答案:

答案 0 :(得分:0)

输出数据df必须为json格式。更改为return df.to_json("records")

此外,也无需执行两次SQL查询。我想用空数据实例化您的datable。由于您正在分配dcc.Interval,因此回调将在实例化n_intervals=0时触发。您所有的查询+转换都可以在回调中进行。