使用 odbc_connect 从 SQLAlchemy 连接到 SQL 服务器

Posted

技术标签:

【中文标题】使用 odbc_connect 从 SQLAlchemy 连接到 SQL 服务器【英文标题】:Connecting to SQL server from SQLAlchemy using odbc_connect 【发布时间】:2018-05-05 03:06:13 【问题描述】:

我是 Python 和 SQL 服务器的新手。在过去的两天里,我一直在尝试将 pandas df 插入我们的数据库,但没有任何运气。谁能帮我调试错误。

我已经尝试了以下

import pyodbc
from sqlalchemy import create_engine

engine = create_engine('mssql+pyodbc:///?odbc_connect=DRIVER=SQL Server;SERVER=bidept;DATABASE=BIDB;UID=sdcc\neils;PWD=neil!pass')
engine.connect()
df.to_sql(name='[BIDB].[dbo].[Test]',con=engine, if_exists='append')

但是在 engine.connect() 行我收到以下错误

sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('08001', '[08001] [Microsoft][ODBC SQL Server Driver]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect)')

谁能告诉我我错过了什么。我正在使用 Microsoft SQL Server Management Studio - 14.0.17177.0

我通过以下方式连接到SQL服务器

Server type: Database Engine
Server name: bidept
Authentication: Windows Authentication

for which I log into my windows using username : sdcc\neils
and password : neil!pass

这个我也试过了

import pyodbc

conn_str = (
    r'Driver=SQL Server Native Client 11.0;'
    r'Server=bidept;'
    r'Database=BIDB;'
    r'Trusted_Connection=yes;'
    )

cnxn = pyodbc.connect(conn_str)

df.to_sql(name='Test',con=cnxn, if_exists='append')

我得到了这个错误

pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Statement(s) could not be prepared. (8180)")

任何帮助将不胜感激,因为我不知道该怎么做。

【问题讨论】:

【参考方案1】:

如SQLAlchemy documentation 中所述,使用传递精确 pyodbc 字符串时,“分隔符必须是 URL 转义”。

所以,这将失败......

import pyodbc
from sqlalchemy import create_engine

params = r'DRIVER=SQL Server;SERVER=.\SQLEXPRESS;DATABASE=myDb;Trusted_Connection=yes'
conn_str = 'mssql+pyodbc:///?odbc_connect='.format(params)
engine = create_engine(conn_str)

...但这会起作用:

import pyodbc
from sqlalchemy import create_engine
import urllib

params = urllib.parse.quote_plus(r'DRIVER=SQL Server;SERVER=.\SQLEXPRESS;DATABASE=myDb;Trusted_Connection=yes')
conn_str = 'mssql+pyodbc:///?odbc_connect='.format(params)
engine = create_engine(conn_str)

【讨论】:

这不适用于 Python 2.7 吗?在 2.7 上找不到解析 AttributeError: 'module' object has no attribute 'parse' 能够在 Python 3.5 上运行它。测试 .to_sql() (它从最后 5 分钟开始运行。并卡在那里......担心它是否会完成) 在 Python2 下它只是 urllib.quote_plus 这适用于 Python 3.5。谢谢你。将看到我如何定期更新表格。最后我收到一个错误,但我可以看到表格错误:C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\sql.py:1168: UserWarning: The provided table name 'Test' is not found exactly as such in the database after writing the table, possibly due to case sensitivity issues. Consider using lower case table names. warnings.warn(msg, UserWarning) 此外,创建的表格在 [sdcc\neils].[Test] 而不是 [dbo].[Test].... 任何人都可以解释我为什么以及我可以做些什么来进入 [dbo] 另外,我收到了这个错误UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 11: ordinal not in range(128),我正在为此使用这个import sys reload(sys) sys.setdefaultencoding('utf8') 我正在为架构打开一个新问题,但在建议的问题中找到了解决方案。我只需要在.to_sql 方法中添加, schema="dbo"

以上是关于使用 odbc_connect 从 SQLAlchemy 连接到 SQL 服务器的主要内容,如果未能解决你的问题,请参考以下文章

如何修复此错误:调用未定义的函数 odbc_connect() [重复]

连接 SAP Hana 数据库时调用未定义函数 odbc_connect() 消息

odbc_connect(): SQL 错误: [unixODBC][Driver Manager]Data source name not found, and no default driver

PHP 警告:odbc_connect():SQL 错误:[Microsoft][ODBC Microsoft Access Driver]一般错误无法打开临时注册表项(易失性)

pdo_odbc 驱动程序问题

PDO连接到ODBC iseries无法正常工作