简体   繁体   English

使用 sqlalchemy 和 pyodbc 连接到 SQL Server 2012

[英]Connecting to SQL Server 2012 using sqlalchemy and pyodbc

I'm trying to connect to a SQL Server 2012 database using SQLAlchemy (with pyodbc) on Python 3.3 (Windows 7-64-bit).我正在尝试在 Python 3.3(Windows 7-64 位)上使用 SQLAlchemy(带有 pyodbc)连接到 SQL Server 2012 数据库。 I am able to connect using straight pyodbc but have been unsuccessful at connecting using SQLAlchemy.我可以使用直接 pyodbc 进行连接,但使用 SQLAlchemy 连接失败。 I have dsn file setup for the database access.我有用于数据库访问的 dsn 文件设置。

I successfully connect using straight pyodbc like this:我像这样使用直接 pyodbc 成功连接:

con = pyodbc.connect('FILEDSN=c:\\users\\me\\mydbserver.dsn')

For sqlalchemy I have tried:对于 sqlalchemy 我试过:

import sqlalchemy as sa
engine = sa.create_engine('mssql+pyodbc://c/users/me/mydbserver.dsn/mydbname')

The create_engine method doesn't actually set up the connection and succeeds, but iIf I try something that causes sqlalchemy to actually setup the connection (like engine.table_names() ), it takes a while but then returns this error: create_engine方法实际上并没有建立连接并成功,但是如果我尝试了一些导致engine.table_names()实际建立连接的方法(如engine.table_names() ),它需要一段时间,然后返回此错误:

DBAPIError: (Error) ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect)') None None

I'm not sure where thing are going wrong are how to see what connection string is actually being passed to pyodbc by sqlalchemy.我不确定哪里出错了,如何查看 sqlalchemy 实际传递给 pyodbc 的连接字符串。 I have successfully using the same sqlalchemy classes with SQLite and MySQL.我已经成功地在 SQLite 和 MySQL 中使用了相同的 sqlalchemy 类。

Thanks in advance!提前致谢!

The file-based DSN string is being interpreted by SQLAlchemy as server name = c , database name = users . SQLAlchemy 将基于文件的 DSN 字符串解释为 server name = c ,database name = users

I prefer connecting without using DSNs, it's one less configuration task to deal with during code migrations.我更喜欢在不使用 DSN 的情况下进行连接,这是在代码迁移期间处理的一项较少的配置任务。

This syntax works using Windows Authentication:此语法适用于 Windows 身份验证:

engine = sa.create_engine('mssql+pyodbc://server/database')

Or with SQL Authentication:或者使用 SQL 身份验证:

engine = sa.create_engine('mssql+pyodbc://user:password@server/database')

SQLAlchemy has a thorough explanation of the different connection string options here . SQLAlchemy 在此处对不同的连接字符串选项进行了详尽的解释。

In Python 3 you can use function quote_plus from module urllib.parse to create parameters for connection:在Python 3,你可以使用函数quote_plus从模块urllib.parse为连接创建参数:

import urllib
params = urllib.parse.quote_plus("DRIVER={SQL Server Native Client 11.0};"
                                 "SERVER=dagger;"
                                 "DATABASE=test;"
                                 "UID=user;"
                                 "PWD=password")

engine = sa.create_engine("mssql+pyodbc:///?odbc_connect={}".format(params))

In order to use Windows Authentication, you want to use Trusted_Connection as parameter:为了使用 Windows 身份验证,您需要使用Trusted_Connection作为参数:

params = urllib.parse.quote_plus("DRIVER={SQL Server Native Client 11.0};"
                                 "SERVER=dagger;"
                                 "DATABASE=test;"
                                 "Trusted_Connection=yes")

In Python 2 you should use functionquote_plus from library urllib instead:在 Python 2 中,您应该改用库urllib函数quote_plus

params = urllib.quote_plus("DRIVER={SQL Server Native Client 11.0};"
                           "SERVER=dagger;"
                           "DATABASE=test;"
                           "UID=user;"
                           "PWD=password")

I have an update info about the connection to MSSQL Server without using DSNs and using Windows Authentication.我有关于不使用 DSN 和使用 Windows 身份验证连接到 MSSQL Server 的更新信息。 In my example I have next options: My local server name is "(localdb)\\ProjectsV12".在我的示例中,我有下一个选项:我的本地服务器名称是“(localdb)\\ProjectsV12”。 Local server name I see from database properties (I am using Windows 10 / Visual Studio 2015).我从数据库属性中看到的本地服务器名称(我使用的是 Windows 10 / Visual Studio 2015)。 My db name is "MainTest1"我的数据库名称是“MainTest1”

engine = create_engine('mssql+pyodbc://(localdb)\ProjectsV12/MainTest1?driver=SQL+Server+Native+Client+11.0', echo=True)

It is needed to specify driver in connection.需要在连接中指定驱动程序。 You may find your client version in:您可以在以下位置找到您的客户端版本:

control panel>Systems and Security>Administrative Tools.>ODBC Data Sources>System DSN tab>Add控制面板>系统和安全>管理工具。>ODBC数据源>系统DSN选项卡>添加

Look on SQL Native client version from the list.从列表中查看 SQL Native 客户端版本。

Just want to add some latest information here: If you are connecting using DSN connections:只想在这里添加一些最新信息:如果您使用 DSN 连接进行连接:

engine = create_engine("mssql+pyodbc://USERNAME:PASSWORD@SOME_DSN")

If you are connecting using Hostname connections:如果您使用主机名连接进行连接:

engine = create_engine("mssql+pyodbc://USERNAME:PASSWORD@HOST_IP:PORT/DATABASENAME?driver=SQL+Server+Native+Client+11.0")

For more details, please refer to the "Official Document"详情请参阅“官方文档”

I did different and worked like a charm.我做了不同的工作,就像一个魅力。

First you import the library:首先导入库:

import pandas as pd
from sqlalchemy import create_engine
import pyodbc

Create a function to create the engine创建一个函数来创建引擎

def mssql_engine(user = os.getenv('user'), password = os.getenv('password')
                 ,host = os.getenv('SERVER_ADDRESS'),db = os.getenv('DATABASE')):
    engine = create_engine(f'mssql+pyodbc://{user}:{password}@{host}/{db}?driver=SQL+Server')
    return engine

Create a variable with your query使用您的查询创建一个变量

query = 'SELECT * FROM [Orders]'

Execute the Pandas command to create a Dataframe from a MSSQL Table执行 Pandas 命令从 MSSQL 表创建数据框

df = pd.read_sql(query, mssql_engine())
import pyodbc 
import sqlalchemy as sa
engine = sa.create_engine('mssql+pyodbc://ServerName/DatabaseName?driver=SQL+Server+Native+Client+11.0',echo = True)

This works with Windows Authentication.这适用于 Windows 身份验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM