未指定驱动程序名称:将Pandas数据框写入SQL Server表

16

我正在尝试将Pandas的DataFrame写入SQL Server表中。以下是我的示例:

import pyodbc
import pandas as pd
import sqlalchemy

df = pd.DataFrame({'MDN': [242342342] })
engine = sqlalchemy.create_engine('mssql://localhost/Sandbox?trusted_connection=yes')
df.to_sql('Test',engine, if_exists = 'append',index = False)
我收到了以下错误信息,请问如何解决?
c:\python34\lib\site-packages\sqlalchemy\connectors\pyodbc.py:82: SAWarning: No driver name specified; this is expected by PyODBC when using DSN-less connections
  "No driver name specified; "


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-25-78677a18ce2d> in <module>()
      4 engine = sqlalchemy.create_engine('mssql://localhost/Sandbox?trusted_connection=yes')
      5 
----> 6 df.to_sql('Test',engine, if_exists = 'append',index = False)
      7 
      8 #cnxn.close()

c:\python34\lib\site-packages\pandas\core\generic.py in to_sql(self, name, con, flavor, schema, if_exists, index, index_label, chunksize, dtype)
    980             self, name, con, flavor=flavor, schema=schema, if_exists=if_exists,
    981             index=index, index_label=index_label, chunksize=chunksize,
--> 982             dtype=dtype)
    983 
    984     def to_pickle(self, path):

c:\python34\lib\site-packages\pandas\io\sql.py in to_sql(frame, name, con, flavor, schema, if_exists, index, index_label, chunksize, dtype)
    547     pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index,
    548                       index_label=index_label, schema=schema,
--> 549                       chunksize=chunksize, dtype=dtype)
    550 
    551 

c:\python34\lib\site-packages\pandas\io\sql.py in to_sql(self, frame, name, if_exists, index, index_label, schema, chunksize, dtype)
   1564                             if_exists=if_exists, index_label=index_label,
   1565                             dtype=dtype)
-> 1566         table.create()
   1567         table.insert(chunksize)
   1568 

c:\python34\lib\site-packages\pandas\io\sql.py in create(self)
    646 
    647     def create(self):
--> 648         if self.exists():
    649             if self.if_exists == 'fail':
    650                 raise ValueError("Table '%s' already exists." % self.name)

c:\python34\lib\site-packages\pandas\io\sql.py in exists(self)
    634 
    635     def exists(self):
--> 636         return self.pd_sql.has_table(self.name, self.schema)
    637 
    638     def sql_schema(self):

c:\python34\lib\site-packages\pandas\io\sql.py in has_table(self, name, schema)
   1577         query = flavor_map.get(self.flavor)
   1578 
-> 1579         return len(self.execute(query, [name,]).fetchall()) > 0
   1580 
   1581     def get_table(self, table_name, schema=None):

c:\python34\lib\site-packages\pandas\io\sql.py in execute(self, *args, **kwargs)
   1465             cur = self.con
   1466         else:
-> 1467             cur = self.con.cursor()
   1468         try:
   1469             if kwargs:

AttributeError: 'Engine' object has no attribute 'cursor'

此外,有没有一种不同于字符串形式的方式来编写 create_engine 的连接字符串呢?我希望能够以字典的形式编写它。

更新:这是我的新环境:

MS SQL Server: Microsoft SQL Server 2012 - 11.0.2100.60 (X64) Feb 10 2012 19:39:15 版权所有 (c) Microsoft Corporation 标准版(64 位)Windows NT 6.2上的(构建 9200:)

Python: 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)]

Pandas版本: '0.16.2'

sqlalchemy版本: 1.1.3

Jupyter服务器版本: 4.2.3

现在关键代码行为:

engine = sqlalchemy.create_engine('mssql+pyodbc://localhost/Sandbox?trusted_connection=yes')

产生以下错误:

c:\python34\lib\site-packages\sqlalchemy\connectors\pyodbc.py:82: SAWarning: No driver name specified; this is expected by PyODBC when using DSN-less connections
  "No driver name specified; "

那么没有办法将数据框转储到 SQL Server 的表中吗? - user1700890
3
你能提供你使用的版本号吗?包括 MS SQL Server 版本、Pandas 版本和 SQLAlchemy 版本。 - MaxU - stand with Ukraine
1
尝试使用 df.to_sql('Test', engine.connect(), if_exists='append', index=False) - Gord Thompson
2
@GordThompson 自 pandas 0.14 以来,这样做是不正确的:https://dev59.com/g4Tca4cB1Zd3GeqPA-sx#26766205 - denfromufa
1
@user1700890,请查看cco的答案 - 我认为它完全回答了你的问题。 - MaxU - stand with Ukraine
显示剩余2条评论
4个回答

32

你需要明确指定你要使用ODBC和要使用的ODBC驱动程序。

engine = sqlalchemy.create_engine('mssql+pyodbc://localhost/Sandbox?driver=SQL+Server+Native+Client+11.0')

默认情况下,信任连接已启用,所以您不需要指定,尽管这样做也不会有害。

更新:
2022-02-18:SQL Server的最新ODBC驱动程序似乎是“ODBC Driver 17 for SQL Server”。名为“SQL Server”的驱动程序已经过时,不应再使用。
@user1718097提供了一个有用的建议:使用[x for x in pyodbc.drivers()]列出已安装的驱动程序。 您还可以使用powershell中的Get-OdbcDriver命令列出已安装的驱动程序。


根据这个答案和SQLAlchemy文档,仅在自定义时需要驱动程序:https://dev59.com/tV8e5IYBdhLWcg3whqo4#25662997 - denfromufa
4
如果您没有使用DSN,则需要驱动程序-请参见问题中的最后一个错误消息。 - cco
@cco 非常感谢您的回答!是否可以将其以字典格式编写?另外,如果我需要提供登录名和密码,该怎么办? - user1700890
2
当我尝试这个时,我不确定我电脑上安装了哪些OBDC驱动程序。导入pyodbc后,我运行了[x for x in pyodbc.drivers()]来获取已安装驱动程序的列表。在我的情况下,只有['SQL Server'],所以我能够包括driver=SQL+Server并且一切正常。 - user1718097
谢谢,这对我有用:engine = create_engine(f"mssql+pyodbc://{username}:{password}@{host}:{port}/{database}?driver=ODBC+Driver+17+for+SQL+Server") - Pedro Henrique
显示剩余2条评论

2
可能的问题是您未指定驱动程序,请尝试使用以下代码:
engine = sqlalchemy.create_engine('mssql+pyodbc://localhost/Sandbox?trusted_connection=yes')

这是基于你在顶部得到的警告信息:

c:\python34\lib\site-packages\sqlalchemy\connectors\pyodbc.py:82: SAWarning: No driver name specified; this is expected by PyODBC when using DSN-less connections
  "No driver name specified; "

请注意,您也可以使用pymssql而不是pyodbc,但微软建议使用后者。
编辑
以下是官方文档,介绍如何连接到/不需要DSN(数据源名称):

https://github.com/mkleehammer/pyodbc/blob/master/docs/index.md#connect-to-a-database


我的环境稍微变了一下,但原始代码和您的建议一样,我仍然得到相同的错误 c:\python34\lib\site-packages\sqlalchemy\connectors\pyodbc.py:82: SAWarning: No driver name specified; this is expected by PyODBC when using DSN-less connections "No driver name specified; " - user1700890

2

我知道这个问题已经有一段时间的答案了,这只是一个警告,但如果您已经正确地转移了所有内容,但仍然出现此错误,那真是令人恼火。

对于那些像我一样必须与之斗争的人,您还可以直接在脚本中输入驱动程序,Pyodbc.py为此提供了可能性(第26-28行):

    # for non-DSN connections, this *may* be used to
    # hold the desired driver name
    pyodbc_driver_name = 'ODBC Driver 17 for SQL Server'


1
以上信息非常有用。下面是我总结的版本,可以帮助初学者进行搜索。
#使用库pandas和pyodbc - 如果没有,请使用pip install命令根据版本安装库。此处使用的Python版本为3.7.8
import pandas as pd
from sqlalchemy import create_engine
import pyodbc
 
  
#This query will work for sql authentication
def mssql_engine():
    engine = create_engine('mssql+pyodbc://type_username:type_password@type_servername_or_localhostname/type_database_name?driver=SQL+Server+Native+Client+11.0')
    return engine

#This query will for windows authentication 
#Note: Uncomment below code for windows authentication
#def mssql_engine():
      #engine = create_engine('mssql+pyodbc://localhostname/db_name?driver=SQL+Server+Native+Client+11.0')
      #return engine
   
 
query = 'select * from table_name'
#using pandas to read from sql and passing connection string as function
df = pd.read_sql(query, mssql_engine() ) 

#printing result
print(df)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接