LoginSignup
0
2

More than 5 years have passed since last update.

Azure SQL Serverのデータテーブルをpyodbcで抽出してみる

Last updated at Posted at 2017-03-13

Microsoft Azure上のSQL Server上のデータを手元(local pc)に持ってきて、pythonのpandas dataframeにするところまでのmemo

試行前提

  • PC OS: Windows 10

  • Python: Python 2.7

  • python libraries: pyodbc,pandas, numpy

  • Azure上のテーブル設定(SQL Server)

    • server: abc_server.database.windows.net
    • database: abc_database
    • username: abc_user
    • password: abc_password
      • それぞれのabc...は、適宜Azure上で設定する時に書き換えて下さい。
  • Azure SQL ServerのFireWall設定を許可しといて下さい

    • そうでないと認証でコケます、、

何はともあれinstall & 初期設定

pyodbcをコマンドプロンプトからinstall

  • 例によってpipにて。
pip install pyodbc

Microsoft ODBC Driver 13 for SQL Server

ではpythonで書いていきましょう。

## libraries
import pyodbc

## initial setting
## 上述の通り、適宜設定値は変えて下さい
server = 'abc_server.database.windows.net'  
database = 'abc_database'  
username = 'abc_user'  
password = 'abc_password'  

## 関数定義
### DB connectionを定義
def db_connection(sv=server, db=database, un=username, pw=password):    
    cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+sv+';DATABASE='+db+';UID='+un+';PWD='+ pw)
    return cnxn.cursor()

### SQLを発行
def query_output(sql):
    cursor.execute(sql)
    row = cursor.fetchone()
    while row:  
        print row[0]  
        row = cursor.fetchone()

Case 1: テーブルの件数(行数)を数える

### DB connectionしときます
cursor = db_connection()

### SalesLT.Customerはテンプレートとしてあるテーブル
sql = 'select count(*) from SalesLT.Customer;' 
query_output(sql) #結果は847

上述に引き続き、テーブル作成はこちらから

Reference

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