LoginSignup
0
0

More than 3 years have passed since last update.

SAS ViyaにSQLite3からデータを取り込む

Posted at

SAS ViyaはAIプラットフォームです。その元になるデータソースとして、CSVやExcel、HTMLなどを指定できますが、さらにSQLite3をそのまま取り込むこともできます。今回はその手順を紹介します。

Viyaに接続する

まず SAS Viyaへ接続します。

from swat import *

cashost='localhost'
casport=5570
useremail='dev@sas.com'
userpassword='password'
casauth='~/.authinfo'
conn = CAS(cashost, casport, useremail, userpassword, caslib="casuser")

SQLite3を準備する

SQLite3のデータベースを用意します。これはCSVから読み込む形で作ります。まずはライブラリのインポートから。

import csv
import sqlite3

次にテーブルを作ります。

sqlc = sqlite3.connect('iris.db')
cur = sqlc.cursor()
cur.execute('''CREATE TABLE iris (
                 sepal_length REAL,
                 sepal_width REAL,
                 petal_length REAL,
                 petal_width REAL,
                 species CHAR(10));
            ''')

そしてCSVファイルの内容をSQLite3のデータベースに取り込みます。データはpandas/iris.csvを使います。この処理はSAS ViyaではなくPythonのSQLite3ライブラリの機能です。

with open('iris.csv', 'r') as iris:
  data = csv.DictReader(iris)
  rows = [ (x['SepalLength'],
             x['SepalWidth'],
             x['PetalLength'],
             x['PetalWidth'],
             x['Name']) for x in data]
cur.executemany('''INSERT INTO iris (sepal_length, 
                                     sepal_width,
                                     petal_length,
                                     petal_width,
                                     species)
              VALUES (?, ?, ?, ?, ?);''', rows)
sqlc.commit()

SQLite3を取り込み

いよいよデータベースを取り込みます。ライブラリを読み込みます。

from swat.cas import datamsghandlers as dmh
dbdmh = dmh.DBAPI(sqlite3, cur, nrecs=10)

取り込みます。

conn.addtable(table='iris_db', caslib='casuser',  **dbdmh.args.addtable)

データを確認する

ちゃんと取り込めたかデータを確認します。

conn.columninfo(table=dict(name='iris_db', caslib='casuser'))
Column ID Type RawLength FormattedLength NFL NFD
0 sepal_length 1 double 8 12 0
1 sepal_width 2 double 8 12 0
2 petal_length 3 double 8 12 0
3 petal_width 4 double 8 12 0
4 species 5 varchar 10 10 0
conn.fetch(table=dict(name='iris_db', caslib='casuser'), to=5)
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2

まとめ

データベースがそのままデータソースとして使えて、さらにSAS Viyaの強力なデータ管理機能が使えるようになります。ぜひお試しください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0