LoginSignup
0
3

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-07-29

はじめに

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

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

1、Windows用DataDirect ODBC Driver for Amazon Redshiftをダウンロードします。

2、手順通りドライバをインストールします。

RedShift接続を設定する

1、ODBC Administratorより「追加」をクリックし、接続定義します。
ドライバは DataDirect 7.1 Amazon Redshift Wire Protocol を選択します。
image.png

2、設定ウィンドウで、以下のようにホスト名、ポート、データソースを入力します。
image.png

3、Test Connectをクリックし、ユーザー名とパスワードで正常に接続できるか確認します。

PythonからRedshiftに接続する

1、PythonからRedshiftにアクセスするには、pyodbcパッケージをインストールします。
以下のコマンドでインストールしてください。

pip install pyodbc

2、以下のようなPythonプログラムで、Redshiftデータにアクセスします。(接続設定を変更ください)

import pyodbc

conn = pyodbc.connect('DSN=Redshift;UID=awsuser;PWD=awsPassword')

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)

3、上記のように接続文字列を定義するか、以下の接続文字列を使用しODBC Administratorでの接続設定を省略できます。

Driver={DataDirect 7.1 Amazon Redshift Wire Protocol}; HostName=ホスト名を設定ください; Database=DB名を設定ください; UID=ユーザIDを設定ください; PWD=パスワードを設定ください; Port=5439

非常に簡単ですね。

参考記事

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

DataDirect for Redshift チュートリアル

0
3
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
3