自己投資としてチャレンジしている内容を Blog で公開しています。
今回は Python による Microsoft SQL Server 用にサンプルデータの一括作成方法について、前回とは異なる方法を紹介します。
Summary
▼1. Python を使ったサンプルデータの作成
本 blog で以前 Python による、サンプルデータの作成方法をお伝えしました。この手順では insert クエリを生成し、sqlcmd で生成した insert クエリを実行する方法でしたが、今回は Python 単体で、テーブルの作成からデータの insert まで完結するコードを紹介します。
Python – SQL Server サンプルデータの作成 No.62
▼2. 事前準備
環境構築などに関しては以下の blog を参考にしてください。
Python – SQL Server on Ubuntu に接続する方法 No.92
▼3. SQL Sever サンプルデータの一括作成
3-1. Python コードの作成
SQL Server には sa のユーザーで接続しています。sa のパスワードは password で指定します。自動で生成したデータを insert 文で生成し、print しています。その後、insert 文を実行し、Select 結果を表示しています。
import pyodbc
import random
import time, datetime, string
server = 'localhost'
database = 'testdb'
username = 'sa'
password = 'password'
driver= '{ODBC Driver 17 for SQL Server}'
success = False
retryc = 0
max_retries = 3
kazu = 10
def randomword(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
while not success and retryc < max_retries:
try:
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+',1433;DATABASE='+database+';UID='+username+';PWD='+ password+';',autocommit=True,Timeout=1,Trusted_Connection='no',Encrypt='no')
cnxn.setencoding('utf-8')
cursor1 = cnxn.cursor()
cursor1.execute("IF DB_ID(N'sampledb1') is null create database sampledb1")
cursor2 = cnxn.cursor()
cursor2.execute("IF NOT EXISTS (select * from sampledb1.dbo.sysobjects where name like 'sampletb') create table sampledb1.dbo.sampletb (id int, num int, cdatetime datetime, note varchar(50))")
num = random.randint(100, 10000000)
dtnow = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
insertquery1 = "insert into sampledb1.dbo.sampletb (id, num,cdatetime,note) values ('"+ str(num) +"','"+ str(num) +"','"+str(dtnow)+"','int')"
for i in range(1,kazu):
insertquery1 = insertquery1 + ",(" + str(i*num) + "," + str(i) + ",'"+ str(dtnow) +"','" + str(randomword(10)) + "')"
print(insertquery1)
cursor3 = cnxn.cursor()
cursor3.execute(insertquery1)
cursor4 = cnxn.cursor()
cursor4.execute("SELECT * FROM sampledb1.dbo.sampletb")
row = cursor4.fetchone()
print("==========================")
print("Results of a select query")
print("==========================")
while row:
print(str(row[0]) + " " + str(row[1]) + " " + str(row[2]) + " " + str(row[3]))
row = cursor4.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:
cursor1.close()
cursor2.close()
cursor3.close()
cursor4.close()
cnxn.close()
3-2. 実行結果
insert into sampledb1.dbo.sampletb (id, num,cdatetime,note) values ('3366109','3366109','2022-12-09 13:59:12','int'),(3366109,1,'2022-12-09 13:59:12','mcranentiv'),(6732218,2,'2022-12-09 13:59:12','orlsojlvuu'),(10098327,3,'2022-12-09 13:59:12','uaclnlkehv'),(13464436,4,'2022-12-09 13:59:12','xngcehsmtc'),(16830545,5,'2022-12-09 13:59:12','llvzgooqaa'),(20196654,6,'2022-12-09 13:59:12','atmordnpfz'),(23562763,7,'2022-12-09 13:59:12','qpzlferdra'),(26928872,8,'2022-12-09 13:59:12','lnbjlmclxx'),(30294981,9,'2022-12-09 13:59:12','xfspqvetbf') ========================== Results of a select query ========================== 3366109 3366109 2022-12-09 13:59:12 int 3366109 1 2022-12-09 13:59:12 mcranentiv 6732218 2 2022-12-09 13:59:12 orlsojlvuu 10098327 3 2022-12-09 13:59:12 uaclnlkehv 13464436 4 2022-12-09 13:59:12 xngcehsmtc 16830545 5 2022-12-09 13:59:12 llvzgooqaa 20196654 6 2022-12-09 13:59:12 atmordnpfz 23562763 7 2022-12-09 13:59:12 qpzlferdra 26928872 8 2022-12-09 13:59:12 lnbjlmclxx 30294981 9 2022-12-09 13:59:12 xfspqvetbf
▼4. 参考情報
- VS Code Python https://code.visualstudio.com/docs/languages/python
- Python – SQL Server サンプルデータの作成 No.62
- Python – SQL Server on Ubuntu に接続する方法 No.92
以上です。参考になりましたら幸いです。