I am looking for a simple and easy to understand way to write into an SQL table in a database. I tried a couple of different ways but still get some errors and don't really know how to interpret them. In my case, I try to write a pandas dataframe, but it could also be 2D numpy array. My current approach is as follows:
# Import libraries:
from pandas.core.frame import DataFrame
from sqlalchemy import create_engine
import urllib
# In this example, a pandas dataframe is created as below:
cols = ['key1', 'locationKey', 'locationGroupKey', 'dayType', 'effectiveFromDate', 'effectiveToDate', 'prctAM0', 'prctAM1', 'prctAM2', 'prctPM0', 'prctPM1', 'prctPM2', 'prctEV0', 'prctEV1', 'prctEV02', 'prctAD']
values = [[178,10218,0,'2018-06-06 00:00:00','2018-06-06 00:00:00','2018-06-06 00:00:00',.33,0,0,.33,0,0,.33,0,0,0],
[178,10218,0,'2018-06-06 00:00:00','2018-06-06 00:00:00','2018-06-06 00:00:00',.33,0,0,.33,0,0,.33,0,0,0],
[178,10218,0,'2018-06-06 00:00:00','2018-06-06 00:00:00','2018-06-06 00:00:00',.33,0,0,.33,0,0,.33,0,0,0],]
df = DataFrame(values, columns = cols)
# Create connection:
quoted = urllib.parse.quote_plus('DRIVER={SQL Server};SERVER=myServername;DATABASE=myDBname;UID=fieldReadUser;PWD=myPW')
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted))
# Write into SQL table:
df.to_sql('tbl_Interval, schema='dbo', con=engine, if_exists='append', index = False)
EDIT: With the suggestions listed below, the code is writing into the table now.
The first argument to to_sql
is just the table name. If you need to specify the schema then you supply it separately as schema=
, eg,
df.to_sql('tbl_Interval', engine, schema='dbo', if_exists='append', index=False)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.