LoginSignup
8

More than 5 years have passed since last update.

DataFrameをMSSQLにINSERTしたい

Posted at

この記事について

.read_csvなどでDataFrameにしたデータをMSSQLに格納したいといった場合に、なるべく簡単に大量データをINSERTする方法はないものかと考えた末に出来上がったものです。bulkinsertは権限が無いことを想定して使いません。

100万行のINSERTに30分くらいかかります。もっと良い方法があったらぜひ教えて下さい。

mssql_insert.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# python 3.5
import pymssql
import pandas as pd

# 前準備
table_name = '[db].[dbo].[sample_table]'
# INSERT先テーブルの型指定
columns = ['%s', '%s', '%d', '%d', '%d', '%d']

# DataFrameを作る
df = pd.DataFrame(...)

# INSERT文生成
args = dict(table=table_name, columns=', '.join(columns))
sql = 'INSERT INTO {table} VALUES ({columns})'.format(**args)

# NaNをNoneに変換
df = df.astype(object).where(pd.notnull(df), None)

params = [tuple(x) for x in df.values]

# SQL実行
cnn = pymssql.connect(host="server", user="sa", password="password", database="db")
cur = cnn.cursor()
cur.executemany(sql, params)
cnn.commit()
cur.close()

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
8