Spotfireはデータ分析には非常に便利なのですが、
解析した結果をデータベースに残すことはできません。
結果をエクスポートしてデータベースにInsertする作業は非効率ですし、
複数のツールを行ったり来たりする手間が非常に面倒くさいです。
そんな時にはやはりPython!
一つのインターフェースで様々な機能を実装できるのはすごく便利です。
Spotfireからデータベースに書き込みをする。
Pythonスクリプトを使用して、Spotfireのマーク済みのデータをSQL Serverに書き込んでみました。
使うデータはBaseBallです。
マークした範囲の選手名をSQL Serverのテーブルに書き込みましょう。
実行イメージ
このようにサラリーが高いのにホームランをあまり打っていなさそうな人を選択してDBに記録します。
ボタンを押すとPythonがSQL ServerにInsertして、処理内容をメッセージボックスで通知します。
実行後のテーブルデータ
ちゃんと4人分入っています。
テーブル定義
書き込み先のテーブルはBaseballRecordという名前で
一カラムしかないのですが一応ソースはこちらです。
CREATE TABLE [dbo].[BaseballRecord]( [Name] [varchar](50) NULL ) ON [PRIMARY] GO
Pythonコード
データベースの接続情報は環境に合わせて変更してください。
#SQL Server Setting import clr clr.AddReference('System.Data') from System.Data import * TheConnection = SqlClient.SqlConnection("server=servername;database=database;uid=sa;password=password") TheConnection.Open() #MsgBox用 clr.AddReference("System.Windows.Forms") from System.Windows.Forms import MessageBox #マークからデータ取得用 from Spotfire.Dxp.Data import DataValueCursor #マークされた行からデータを抽出 myCursor = DataValueCursor.CreateFormatted(Document.Data.Tables["Baseball"].Columns["Player Name"]) markedRows = Document.Data.Markings["マーク"].GetSelection(Document.Data.Tables["Baseball"]).AsIndexSet() totalCount = 0 #SQL Serverへアクセス for row in Document.Data.Tables["Baseball"].GetRows(markedRows, myCursor): print myCursor.CurrentValue # 処理SQLの作成と実行 sqlcmd = "insert into BaseballRecord values ( '" + myCursor.CurrentValue +"')" MyAction = SqlClient.SqlCommand( sqlcmd , TheConnection) totalCount += MyAction.ExecuteNonQuery() TheConnection.Close() MessageBox.Show( str(totalCount) + "人分追加しました。")
挿入処理後にデータテーブルをリフレッシュ
スクリプトを少し改良しました。
Insert対象のBaseballRecordテーブルをデータテーブルとして追加して、
処理後にリロードをするようにしました。
これでボタンを押した後に追加データを確認できます。
スクリプトとしては最初と最後に数行追加したのみです。
#テーブルリフレッシュ用に追加 from Spotfire.Dxp.Data import * from Spotfire.Dxp.Data.Import import * #SQL Server Setting import clr clr.AddReference('System.Data') from System.Data import * TheConnection = SqlClient.SqlConnection("server=servername;database=database;uid=sa;password=password") TheConnection.Open() #MsgBox用 clr.AddReference("System.Windows.Forms") from System.Windows.Forms import MessageBox #マークからデータ取得用 from Spotfire.Dxp.Data import DataValueCursor #マークされた行からデータを抽出 myCursor = DataValueCursor.CreateFormatted(Document.Data.Tables["Baseball"].Columns["Player Name"]) markedRows = Document.Data.Markings["マーク"].GetSelection(Document.Data.Tables["Baseball"]).AsIndexSet() totalCount = 0 #SQL Serverへアクセス for row in Document.Data.Tables["Baseball"].GetRows(markedRows, myCursor): print myCursor.CurrentValue # 処理SQLの作成と実行 sqlcmd = "insert into BaseballRecord values ( '" + myCursor.CurrentValue +"')" MyAction = SqlClient.SqlCommand( sqlcmd , TheConnection) totalCount += MyAction.ExecuteNonQuery() TheConnection.Close() MessageBox.Show( str(totalCount) + "人分追加しました。") # Refresh table Document.Data.Tables["BaseballRecord"].Refresh()