2011-09-06 52 views
35

是否有可用于连接MSSQL和Python 2.7的模块?python中的MSSQL 2.7

我下载了pymssql,但它是用于python 2.6的。 python 2.7有没有等效的模块?

我不知道如果任何人可以提供链接。


重要提示:同时还有一个pymssql模块可用。千万不要错过这个页面的最后读了答案:https://stackoverflow.com/a/25749269/362951

+0

是不是2.7向后兼容2.6?即不是该模块在2.6中工作? – rplnt

+0

没有安装http://code.google.com/p/pymssql/downloads/detail?name=pymssql-1.9.908.win32-py2.6.exe&can=2&q=它检查python版本并结束设置 – Shashi

+2

有2.7快照http://build.damoxc.net/downloads/pymssql/snapshots/ ...如果有帮助。 – rplnt

回答

52

您还可以使用pyodbc连接从Python来MSSQL。

一种example from the documentation

import pyodbc 
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass') 
cursor = cnxn.cursor() 
cursor.execute("select user_id, user_name from users") 
rows = cursor.fetchall() 
for row in rows: 
    print row.user_id, row.user_name 

SQLAlchemy文库(在另一个答案提到的),使用pyodbc连接到MSSQL数据库(它会尝试各种库,但pyodbc是优选的)。示例代码中使用的SQLAlchemy:

from sqlalchemy import create_engine 
engine = create_engine("mssql://me:[email protected]/testdb") 
for row in engine.execute("select user_id, user_name from users"): 
    print row.user_id, row.user_name 
+3

https://github.com/mkleehammer/pyodbc – ALH

4

使用PIP如下安装pyodbcpip install pyodbc

import pyodbc 
cnxn = pyodbc.connect("DRIVER={SQL Server};SERVER=SOME-PC;DATABASE=my_db") 
cursor = cnxn.cursor() 


cursor.execute("insert into test_tb values(6, 'name')") 

cursor.execute("select id, name from my_tb") 
rows = cursor.fetchall() 
for row in rows: 
    print row.id, row.name 

有关详细信息,请参阅

https://github.com/mkleehammer/pyodbc/wiki

+0

这个pip安装不再看起来像工作(Ubuntu 16.04,Python 2.7。):'--compile failed and error code 1 in ...' –

+2

@MichaelMügge - 'pip install pyodbc'在Ubuntu 16.04上运行正常,如果你先安装'sudo apt install unixodbc-dev'。 –

+0

@GordThompson,的确。那里的重要细节。谢谢。 –

17

如果你碰到这个问题,通过未来网页搜索,请注意pymssql时下确实支持Python 2.7(和3.3)或更新版本。无需使用ODBC。

pymssql要求:

的Python 2.x的:2.6或更高版本。 Python 3.x:3.3或更新版本。

请参阅http://pymssql.org/