我正在尝试将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) 2012年2月10日19:39:15 版权所有(c)Microsoft Corporation Windows NT 6.2上的标准版(64位)(Build 9200:)
Python:3.4.3(v3.4.3:9b73f1c3e601,2015年2月24日,22:43:06)[MSC v.1600 32 bit(Intel)]
熊猫版:'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; "
答案 0 :(得分:16)
您需要同时指定要使用ODBC和要使用的ODBC驱动程序。
engine = sqlalchemy.create_engine('mssql+pyodbc://localhost/Sandbox?driver=SQL+Server+Native+Client+11.0')
可信连接是默认连接,因此您不需要指定它,尽管这样做不应该受到伤害。
答案 1 :(得分: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,但MS建议使用后者。
修改
以下是有关如何连接/不连接DSN(数据源名称)的官方文档:
https://github.com/mkleehammer/pyodbc/blob/master/docs/index.md#connect-to-a-database
答案 2 :(得分:1)
我知道这个问题已经回答了一段时间,这只是一个警告,但是如果您正确传输了所有内容,并且仍然出现此错误,那就很烦人了。
对于所有像我一样不得不为此苦苦挣扎的人,您也可以直接在脚本中输入驱动程序, Pyodbc.py 为此提供了可能性(第26-28行):< / p>
# for non-DSN connections, this *may* be used to
# hold the desired driver name
pyodbc_driver_name = 'ODBC Driver 17 for SQL Server'
答案 3 :(得分:1)
以上信息非常有用。在下面评论我的合并版本,可以帮助新人在搜索过程中。
#using library 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)