Windows和Linux下使用Python访问SqlServer的方法介绍

yipeiwu_com5年前Python基础

经常用Python写demo来验证方案的可行性,最近遇到了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")

这里只是写了简单的demo来验证可行性,希望对你有帮助。

相关文章

Python version 2.7 required, which was not found in the registry

Python version 2.7 required, which was not found in the registry

安装PIL库的时候,直接提示:Python version 2.7 required, which was not found in the registry。 如图: 大意是说找不到...

使用Python微信库itchat获得好友和群组已撤回的消息

使用Python微信库itchat获得好友和群组已撤回的消息

具体代码如下所述: #coding=utf-8 import itchat from itchat.content import TEXT from itchat.content i...

解决Python3中的中文字符编码的问题

解决Python3中的中文字符编码的问题

python3中str默认为Unicode的编码格式 Unicode是一32位编码格式,不适合用来传输和存储,所以必须转换成utf-8,gbk等等 所以在Python3中必须将str类型...

Python编程语言的35个与众不同之处(语言特征和使用技巧)

一、Python介绍   从我开始学习Python时我就决定维护一个经常使用的“窍门”列表。不论何时当我看到一段让我觉得“酷,这样也行!”的代码时(在一个例子中、在StackOverfl...

pip install urllib2不能安装的解决方法

python35 urllib2 不能用 Could not find a version that satisfies the requirement urllib2 (from...