Python – SQL Server on Ubuntu 検索結果をファイルに保存 No.95

自己投資としてチャレンジしている内容を Blog で公開しています。今回は pyodbc を使い python で SQL Server に接続後、Select の結果をローカルのファイルに保存する方法を紹介します。

▼1. Python で SQL Server に接続し、Select の結果をファイルに保存

本 blog で以前 Java により、検索結果をファイルに保存する方法を案内しました。今回は python で実装します。

Java – SQL Server Select 実行結果をテキストに保存 No.70


▼2. 事前準備

環境構築などに関しては以下の blog を参考にしてください。

Python – SQL Server on Ubuntu に接続する方法  No.92


▼3. SQL Server に接続し、Select の結果をファイルに保存する Python コード

3-1. Python コードの作成

Cursor.fetchone() メソッドを利用し、Select 結果を取り込んでファイルに出力します。

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

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('/home/xxx/results.txt', '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()

3-2. 実行結果

エラーなく実行した結果、results.txt のファイルが作成されます。

表示されている c1 列の 1,2,3 は事前に insert していたレコードで、3790247  はコードの中でランダムに生成された数です。

# results.txt
1 1
2 2
3 3
10 10
3790247 3790247

▼4. 参考情報

  1. Java – SQL Server Select 実行結果をテキストに保存 No.70
  2. Python – SQL Server on Ubuntu に接続する方法  No.92
  3. cursor.fetchone() https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchone.html

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



コメントを残す

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