반응형
/*******************************************************************************************************************
-- Title : [Py3.5] Insert Dataframe into SQL Server w/ Pymssql
-- Reference : googling
-- Key word : dataframe data frame sql server pymssql insert 데이터프레임 데이터 프레임 저장
*******************************************************************************************************************/
■ Script
import pymssql
import pandas as pd
# ------------------------------
# -- Create Dataframe
# ------------------------------
df = pd.DataFrame({"a_key":[111,222,333], "b_sect":['a1','a2','a3',],
"c_mop":["aaaaa","bbbbb","ccccc"], "d_mop":["aaaaa","bbbbb","ccccc"],
"e_mop":["aaaaa","bbbbb","ccccc"], "f_mop":["aaaaa","bbbbb","ccccc"]})
print (df)
print ("... dataframe", "." * 100, "\n")
# ------------------------------
# -- Connection String
# ------------------------------
conn = pymssql.connect(host='hostname', user='user', password='password', database='db')
cur = conn.cursor()
# ------------------------------
# -- Create SQL
# ------------------------------
sql = "insert into mop.cn values(%d, %s, %s, %s, %s, %s);"
data = [tuple(x) for x in df.values]
print("sql:", sql)
print("data:", data)
print (",,, sql_statement", "," * 100, "\n")
# ------------------------------
# -- Execute SQL
# ------------------------------
cur.executemany(sql, data)
conn.commit()
반응형