python访问sqlserver示例
最近遇到了Python访问SqlServer的问题,这里总结下。
一、Windows下配置Python访问Sqlserver
环境:Windows 7 + Sqlserver 2008
1、下载并安装pyodbc
下载地址:http://code.google.com/p/pyodbc/downloads/list
2、访问SqlServer
>>> import pyodbc
>>>cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=192.168.1.100\\sql;DATABASE=testDB;UID=sa;PWD=myPassword')
>>>cursor = cnxn.cursor()
>>>cursor.execute("select * from Tb")
二、Linux下配置Python访问SqlServer
环境:CentOS 6.2 + Sqlserver 2008
1、安装freetds:
yum install freetds*
2、安装pyodbc:
yum install pyodbc
修改odbc配置:
vi /etc/odbcinst.ini
添加FreeTDS驱动:
[SQL Server]
Description = FreeTDS ODBC driver for MSSQL
Driver = /usr/lib/libtdsodbc.so
Setup = /usr/lib/libtdsS.so
FileUsage = 1
3、测试
#python
>>> import pyodbc
>>>cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=192.168.1.100\\sql;DATABASE=testDB;UID=sa;PWD=myPassword')
>>>cursor = cnxn.cursor()
>>>cursor.execute("select * from Tb")