Python -pyodbcでMySQLに接続し検索結果を Azure Blob Storage に保存  No.102

自己投資としてチャレンジしている内容を Blog で公開しています。

今回は python で pyodbc を使い MySQL に接続し Select 結果を Azure Blob Storage にファイルとして保存する方法について紹介します。

▼1. pyodbc による MySQL への検索結果をAzure Blob Storage に保存

本 blog では以前、Python による MySQL への接続および検索結果のファイル保存について紹介していましたが、今回はそのファイルを Azure Blob Storage へ保存したいと思います。

Python – pyodbc で MySQL に接続し検索結果をファイルに保存  No.99


▼2. 事前準備

環境、事前準備などに関しては以下の blog を参考にしています。

Python – pyodbc で MySQL on Ubuntu 20.04 に接続する方法  No.98


▼3. MySQL に接続し 検索結果を Azure Blob Storage に保存する Python コード

3-1. python コードを作成

Python のコード savemysqldata2blob.py を作成します。環境に合わせてパラメータを変更します。

MySQL で実行した結果を一旦 result5.txt に保存し、そのファイルを読んで Azure Blob Storage に別のファイル名 results10.txt として保存しています。

import pyodbc
import random
import time, datetime, string

driver = '{MYSQL ODBC 8.0 Driver}'
server = 'localhost'
dbname = 'testdb'
user = 'hiveuser'
pw = 'hivepassword'
query = "select * from testtbl"
success = False
retryc = 0
max_retries = 3
connection_string = 'DefaultEndpointsProtocol=https;AccountName=xxxx;EndpointSuffix=core.windows.net'
local_filename = '/home/xxx/results5.txt'
container_name = "files"
blob_name = "results10.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:
        conn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=3306;DATABASE='+dbname+';UID='+user+';PWD='+pw+';')
        cursor = conn.cursor()
        cursor.execute(query)
        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(15)

# 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)

# if success is success, close the cursor and connection
if success:
    cursor.close()
    conn.close()

3-2. 実行結果

エラーなく実行した結果が以下です。Blob Storage に保存されたファイル名がリストされます。

python3 savemysqldata2blob.py

results10.txt

出力されたファイルの中身を確認。

cat results10.txt

1 1
2 2
3 3

▼4. 参考情報

  1. Python – pyodbc で MySQL に接続し検索結果をファイルに保存  No.99
  2. Python – pyodbc で MySQL on Ubuntu 20.04 に接続する方法  No.98
  3. Python in Visual Studio Code

以上です。参考になりましたら幸いです。




コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です