使用odbc_connect从SQLAlchemy连接到SQL Server

时间:2017-11-21 15:27:19

标签: python sql-server pandas sqlalchemy pyodbc

我是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 个答案:

答案 0 :(得分:4)

SQLAlchemy documentation中所述,"分隔符必须是网址转义"当使用传递精确的pyodbc字符串时。

所以,这会失败......

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)