Home > Backend Development > Python Tutorial > Windows和Linux下使用Python访问SqlServer的方法介绍

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

WBOY
Release: 2016-06-06 11:21:48
Original
1219 people have browsed it

经常用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来验证可行性,希望对你有帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template