如何将数据从dataFrame加载到mssql表

时间:2018-05-05 07:51:31

标签: python pandas sqlalchemy pandas-to-sql

engine = sqlalchemy.create_engine('mssql+pyodbc://<Username>:<password>@<DBServername>/<DBName>', pool_pre_ping=True)

我有数据要加载到DataFrame中,当我遍历DF中的每一行时使用连接字符串我能够将数据插入表中(使用INSERT INTO ..语句一次一行) 但我想使用<DataFrame>.to_sql("<Table_name>", engine, if_exists='append')

如果我遗失了什么,请帮助我理解?

但我一直收到此错误

/Library/Python/2.7/site-packages/sqlalchemy/connectors/pyodbc.py:79: SAWarning: No driver name specified; this is expected by PyODBC when using DSN-less connections
  "No driver name specified; "
Traceback (most recent call last):
  File "/Users/snaidu/renuka/python-projects/staging/test.py", line 131, in <module>
    print(loaddmvcsvfile())
  File "/Users/snaidu/renuka/python-projects/staging/test.py", line 115, in loaddmvcsvfile
    result.to_sql("table1", engine, if_exists='append')
  File "/Library/Python/2.7/site-packages/pandas/core/generic.py", line 1534, in to_sql
    chunksize=chunksize, dtype=dtype)

1 个答案:

答案 0 :(得分:0)

您需要指定要使用的SQL驱动程序,对于MS-SQL,这将是本机驱动程序SQL Server Native Client 11.0

所以例如你可以使用这样的东西:

cxn_string = 'mssql+pyodbc://<Username>:<password>@<DBServername>/<DBName>?driver=SQL+Server+Native+Client+11.0'
engine = sqlalchemy.create_engine(cxn_string, pool_pre_ping=True)

但这有点长,难以阅读,所以我通常会做一个辅助函数,就像这样

import sqlalchemy
import urllib

def sql_connect(server, username, password, database, **kwargs):
'''Connect to SQL server'''
parameters = {'driver': 'SQL Server Native Client 11.0'}

string = r'mssql+pyodbc://{username}:{password}@{server}/{database}?{parameters}'
cxn_string = string.format(server=server,
                           username=username,
                           password=password,
                           database=database,
                           parameters=urllib.parse.urlencode(parameters))
return sqlalchemy.create_engine(cxn_string, **kwargs)