Linux下Python访问SQLServer

以root权限操作


1.安装unixODBC 【下载地址http://www.unixodbc.org/】

sh configure --prefix=/usr/local/unixODBC

make

make install


2.安装freetds 【下载地址http://www.freetds.org/software.html】

sh configure -prefix=/usr/local/freetds --with-unixodbc=/usr/local/unixODBC /

-with-tdsver=8.0 -enable-msdblib -enable-dbmfix -with-gnu-ld -enable-shared -enable-static

make

make install


注:指明--with-unixodbc=/usr/local/unixODBC可以生成libtdsodbc.so


3.配置unixODBC


进入/usr/local/unixODBC

创建文件tds.driver.template


[TDS]

Description = FreeTDS Driver for Linux & MSSQL on Win32

Driver = /usr/local/freetds/lib/libtdsodbc.so

Setup = /usr/local/freetds/lib/libtdsS.so

保存后执行命令


bin/odbcinst -i -d -f tds.driver.template


创建文件tds.datasource.template


[my_data]

Description = Connection to windows virtual machine

Driver = TDS

Trace = No

Database = aa

Server = 192.168.7.3

Port = 1433

TDS_Version = 8.0

保存后执行命令


bin/odbcinst -i -s -l -f tds.datasource.template


4.测试freetds和unixODBC

进入/usr/local/freetds/目录下

执行命令

bin/tsql -H192.168.7.3 -p1433 -Usa -Padmin1234

1>use aa

2>select * from sysfiles

3>go

再进入

/usr/local/unixODBC

执行命令

bin/isql my_data sa admin1234

SQL>select * from sysfiles


5.安装pyODBC 【下载地址http://code.google.com/p/pyodbc/】

首先安装python2.4.4版,步骤:

./configure

make

make install

然后编译安装

python setup.py install

注:如果编译出错,请

cp /usr/local/unixODBC/include/* /usr/include/

cp /usr/local/unixODBC/lib/* /usr/lib/

然后再运行


6.python测试代码

import pyodbc

conn = pyodbc.connect("DSN=my_data;UID=sa;PWD=admin1234;DATABASE=aa;")

sql = 'select * from sysfiles'

cursor = conn.cursor()

cursor.execute(sql)

rs = cursor.fetchall()

if len(rs) > 0:

for i in range(0, len(rs)):

row = rs[i]

print row[0]

cursor.close()

conn.close()


*7.如果其他账户下使用pyodbc

将第5步生成的文件pyodbc.so复制到zenoss的python目录下

cp /usr/local/lib/python2.4/site-packages/pyodbc.so /opt/zenoss/lib/python2.4/site-packages/

【pyodbc.so可能位于/usr/lib/python2.4/site-packages/目录下】

这样就可以zenoss用户使用pyodbc了


你可能感兴趣的:(linux,python,sqlserver)