LoginSignup
1
2

More than 3 years have passed since last update.

Linux上のPythonアプリからAmazon RedshiftにODBCでデータ連携

Posted at

はじめに

この記事では、DataDirectドライバを利用し、Linux、UNIX上のPythonアプリケーションからAmazon RedshiftにODBCで簡単にデータ連携する方法を解説します。

unixODBCをインストールする

1、以下のコマンドで、unixODBCパッケージをインストールします。

CentOSの場合

sudo yum install unixODBC-devel unixODBC

Ubuntu/Debianの場合

sudo apt-get install unixODBC-dev unixODBC

2、unixODBCのインストール後、
/home//Progress/DataDirect/ODBC_80_64bit/odbcinst.ini

の内容を、

/etc/odbcinst.ini

に貼り付けます。

Amazon Redshift用DataDirectドライバのインストール

1、DataDirect ODBC Driver for Amazon Redshiftをダウンロードします。
2、以下のコマンドを実行し、パッケージを展開します。

ar -xvf PROGRESS_DATADIRECT_ODBC_REDSHIFT_LINUX_64.tgz

3、binファイルを実行し、ドライバをインストールします。

./ PROGRESS_DATADIRECT_ODBC_8.0_LINUX_64_INSTALL.bin

4、インストール完了後、インストールフォルダに移動し、シェルスクリプト odbc.sh または odbc.csh を実行し、環境変数を設定します。

5、これで3つの環境変数が設定されます。正しく設定されているかどうかを確認し、先に進みましょう!

[progress@centos7264 ODBC_80_64bit]$ echo $LD_LIBRARY_PATH && echo $ODBCINI && echo $ODBCINST
/home/progress/Progress/DataDirect/ODBC_80_64bit/lib:/home/progress/Progress/DataDirect/ODBC_80_64bit/jre/lib/amd64/server
/home/progress/Progress/DataDirect/ODBC_80_64bit/odbc.ini
/home/progress/Progress/DataDirect/ODBC_80_64bit/odbcinst.ini

PythonからRedshiftに接続する

1、Linux、Unix上yPthonアプリケーションよりRedshiftにアクセスするには、pyodbcパッケージをインストールしなくてはなりません。
以下のコマンドでインストールしてください。

pip install pyodbc

2、以下のサンプルPythonプログラムで、Redshiftからデータにアクセスしてみましょう。

import pyodbc

conn = pyodbc.connect('Driver={DataDirect 8.0 Amazon Redshift Wire Protocol}; HostName=redshift-cluster-1.cy1mp8nn6ntk.us-west-2.redshift.amazonaws.com; Database=dev; UID=awsuser; PWD=Galaxy472; Port=5439')

cursor = conn.cursor()

## Create Tables
cursor.execute("CREATE TABLE Track ( TrackId INT NOT NULL, Name VARCHAR(200) NOT NULL, AlbumId INT, MediaTypeId INT NOT NULL, GenreId INT, Composer VARCHAR(220), Milliseconds INT NOT NULL, Bytes INT, UnitPrice NUMERIC(10,2) NOT NULL);")

cursor.execute("INSERT INTO Track (TrackId, Name, AlbumId, MediaTypeId, GenreId, Composer, Milliseconds, Bytes, UnitPrice) VALUES (1, 'For Those About To Rock (We Salute You)', 1, 1, 1, 'Angus Young, Malcolm Young, Brian Johnson', 343719, 11170334, 0.99);")

conn.commit()

##Access Data using SQL
cursor.execute("select * from Track")
while True:
    row = cursor.fetchone()
    if not row:
        break
    print(row)

##Access Data using SQL
cursor.execute("select * from Artist")
while True:
    row = cursor.fetchone()
    if not row:
        break
    print(row)

非常に簡単ですね。

参考記事

Amazon Redshiftへのリアルタイムアクセス

DataDirect for Redshift チュートリアル

1
2
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
1
2