自己投資としてチャレンジしている内容を Blog で公開しています。今回は pyodbc を使い python で SQL Server に接続し、Select 結果をファイルとして、Azure Blob Storage に保存する方法を紹介します。
Summary
▼1. Python で SQL Server に接続し Select の結果を Azure Blob Storage に保存
本 blog で以前 Java により、検索結果をファイルに保存し Azure Blob Storage に保存する方法を案内しました。今回は python で実装します。
Java – SQL Server 検索結果をAzure Blob Storage に保存 No.75
▼2. 事前準備
環境構築などに関しては以下の blog を参考にしてください。
Python – SQL Server on Ubuntu に接続する方法 No.92
▼3. Select の結果を Azure Blob Storage に保存する Python コード
3-1. Python コードの作成
Azure Blob Storage の接続文字列を connection_string に指定し、Storage の Account key で接続しています。Select 結果を results.txt としてローカルに保存し、そのファイルを Blob Storage に保存しています。保存後、blob storage のコンテイナーにあるファイルをリスト (表示) しています。
SQL Server および Azure Blob Storage の認証情報や、ファイル名などのパラメータは手元の環境に合わせ変更ください。
import time
import pyodbc
import random
import datetime
server = 'localhost'
database = 'testdb'
username = 'sa'
password = 'yourpassword'
driver= '{ODBC Driver 17 for SQL Server}'
success = False
retryc = 0
max_retries = 3
connection_string = 'DefaultEndpointsProtocol=https;AccountName=xxxx;AccountKey=xxxxcore.windows.net'
local_filename = '/home/xxxx/results.txt'
container_name = "files"
blob_name = "results.txt"
from azure.storage.blob import BlobServiceClient
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
# create a container and a blob client
container_client = blob_service_client.get_container_client(container_name)
blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
while not success and retryc < max_retries:
try:
# create random number
num = random.randint(100, 10000000)
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+',1433;DATABASE='+database+';UID='+username+';PWD='+ password+';',autocommit=False,Timeout=1,Trusted_Connection='no',Encrypt='no')
cursor0 = cnxn.cursor()
cursor0.execute("insert into sampledb.dbo.sampletb values ("+ str(num) + ","+ str(num) + ")")
cursor0.commit()
cursor = cnxn.cursor()
cursor.execute("SELECT * FROM sampledb.dbo.sampletb")
row = cursor.fetchone()
# save the results each line to a file
with open(local_filename, 'w') as f:
while row:
f.write(str(row[0]) + " " + str(row[1]) + "\n")
row = cursor.fetchone()
success = True
except pyodbc.Error as ex:
retryc += 1
print("Current Timestamps:" + str(datetime.datetime.now()) + "retry count: " + str(retryc))
print("==========================")
print("Error: " + str(ex))
print("==========================")
time.sleep(3)
finally:
cursor.close()
# upload the file to blob storage
with open(local_filename, "rb") as data:
blob_client.upload_blob(data)
# list the blobs in the container
blob_list = container_client.list_blobs()
for blob in blob_list:
print("\t" + blob.name)
3-2. 実行結果
python3 ./saveblobstorage.py
results.txt
▼4. 参考情報
- Java – SQL Server 検索結果をAzure Blob Storage に保存 No.75
- Python – SQL Server on Ubuntu に接続する方法 No.92
- Sample code azure-sdk-for-python/blob_samples_authentication.py at main · Azure/azure-sdk-for-python · GitHub
- クイック スタート: Python 用 Azure Blob Storage クライアント ライブラリ | Microsoft Learn
以上です。参考になれば幸いです。