Spotfire加载数据方式一般为全量加载,即使数据无更新或者只更新一小部分,这种方式在数据量大时会导致加载过慢,影响性能,也会大量占用服务期资源,影响系统运行。那能否实现增量加载数据呢?即每次只加载更新的部分数据。答案是可以的
方法1:IronPython实现
“get_data_from_sql”脚本如下:
#sql脚本读取数据库
from Spotfire.Dxp.Data.Import import DatabaseDataSource,DatabaseDataSourceSettings,DataTableDataSource
from Spotfire.Dxp.Application.Visuals import Visualization
from Spotfire.Dxp.Data import AddRowsSettings
sqlCommand=Document.Properties['sql'] + " AND MINUTE_TIMEKEY > '%s'"%lastTimekey #'2023-06-29 18:05'
username = Document.Properties['username']
password = Document.Properties['password']
dbsettings = DatabaseDataSourceSettings( "System.Data.OracleClient","Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.10.10.11)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));User Id=%s;Password=%s"%(username,password),sqlCommand)
dataSource = DatabaseDataSource(dbsettings)
table_name = "the_result_table"
if not Document.Data.Tables.Contains(table_name):
Document.Data.Tables.Add(table_name, dataSource)
elif Document.Properties['Generatetype'] == "增加":
rowsettings=AddRowsSettings(Document.Data.Tables[table_name],dataSource)
Document.Data.Tables[table_name].AddRows(dataSource,rowsettings)
else:
Document.Data.Tables[table_name].ReplaceData(dataSource)
#自动在表中显示
showtable = showtable.As[Visualization]() # 1. Change the data table
newTable = Document.Data.Tables.Item[table_name]
showtable.Data.DataTableReference = newTable
showtable.TableColumns.Clear() #清空列
for i in newTable.Columns:
showtable.TableColumns.Add(i)
for i in showtable.TableColumns:
i.Width = 200
其中属性Generatetype对应上面文本区域中的“更新方式”;lastTimekey是需要传入参数,其表达式为:对应输出表的Max([MINUTE_TIMEKEY])
这个方法有个问题:获取过数据后将模板保存,重新打开后需要输入数据库的用户名和密码,如果获取过多次,则需要输入多次用户名和密码,很繁琐,因此一定要点击“删表”删除表后再保存模板。
方法2:自定义函数实现
“get_data_from_sql”对应的自定义函数代码:
import pandas as pd
import cx_Oracle
if sql =='':
table_from_sql == pd.DataFrame([['']])
else:
db = cx_Oracle.connect('username','password','10.10.10.11:1521/orcl')
lastTimekey = last_timekey if len(last_timekey)>0 else '2023-07-03 11:40'
sqlcommand = sql + " AND MINUTE_TIMEKEY > '%s'"%lastTimekey #'2023-07-03 11:40'
table_from_sql = pd.read_sql(sqlcommand,db)
last_timekey = table_from_sql.MINUTE_TIMEKEY.max()
输入参数为sql,输出参数为主表table_from_sql(首次输出到新表,以后更具需求,如果是增量,则选择增加行,否则选择替换表),以及更新时间last_timekey(输出到一个文档属性,作为下次更新的起始时间),设置方法可参考我的另一篇文章Spotfire将输入数据生成表_jogarys的博客-CSDN博客
自定义函数方式没有上面要重复输入密码的问题,但设置增量方式需要手动选择一下。