ubuntu下ODBC访问mssql和sybase(perl&python)

一、安装freetds

参考http://my.oschina.net/u/2245781/blog/626203

二、安装unixodbc

sudo  apt-get install unixodbc unixodbc-bin unixodbc-dev

三、获取DBD-ODBC

wget  http://www.cpan.org/authors/id/M/MJ/MJEVANS/DBD-ODBC-1.52.tar.gz

四、安装

tar xzvf DBD-ODBC-1.52.tar.gz 

 cd DBD-ODBC-1.52/

 perl Makefile.PL -o /usr

make&sudo make install

五、配置(freetds已配置好

/etc/odbcinst.ini加上

# setup from FreeTDS package
[FREETDS]
Description     = ODBC of FreeTDS for MS SQL 2000
Driver          = /opt/local/freetds/lib/libtdsodbc.so
Setup          	= /opt/local/freetds/lib/libtdsodbc.so
Trace 		=	Yes
TraceFile	=/opt/local/freetds/odbcinst.log
UsageCount	= 1

/etc/odbc.ini加上

[mysql]
Driver		= /opt/local/mysql-connector/lib/libmyodbc3_r.so
SETUP		= /opt/local/mysql-connector/lib/libmyodbc3_r.so 
UsageCount	= 1

六、测试

perl的dbi数据访问odbc读取sqlserver数据被截断的问题(http://www.lai18.com/content/683266.html),需在perl代码加上

$dbh->{LongTruncOk}=1; 

$dbh->{LongReadLen} = 1048576*1024;

#!/usr/bin/perl
 
use DBI;

 
$dbname="mymotif";
$user="mymotif";
$passwd="wxwpxh";
 

#mssql 字串对应于 /etc/odbc.ini 里面的 [mssql] 
$dsn = "DBI:ODBC:mssql";
  
 
$dbh = DBI->connect($dsn,$user,$passwd) or die "can't connect to database : $DBI::errstr";
$dbh->{LongTruncOk}=1; 
$dbh->{LongReadLen} = 1048576*1024;

$sth=$dbh->prepare("select * from STUDENT");
$sth->execute;
while (@recs=$sth->fetchrow_array) {
print $recs[0].":".$recs[1].":".$recs[2]."\n";
}
$dbh->disconnect;

七、sybase

odbc配置:/etc/odbcinst.ini不变

/etc/odbc.ini加上

[sybase]
Description	= Sybase SQL Server
Driver		= FREETDS
Servername	= egServer50
Database	= testdb

如果环境变量TDSVER的值不是5.0,则需要在perl代码中设置如下:

#!/usr/bin/perl

use DBI;
use DBD::ODBC; 


$user="mymotif";
$passwd="wxwpxh";
$ENV{TDSVER} = "5.0";

#sybase 字串对应于 /etc/odbc.ini 里面的 [DSN] 
$dsn = "DBI:ODBC:sybase";
 

$dbh = DBI->connect($dsn,$user,$passwd) or die "can't connect to database : $DBI::errstr";

$sth=$dbh->prepare("select * from STUDENT");
$sth->execute;

$sth->{'LongTruncOk'} = 1;
while (@recs=$sth->fetchrow_array) {
	print $recs[0].":".$recs[1].":".$recs[2]."\n";
}
$dbh->disconnect;

而在python代码中设置如下

#coding=utf-8
import pyodbc
import os
os.environ["TDSVER"]="5.0"

conn =  pyodbc.connect("DSN=sybase;UID=mymotif;PWD=wxwpxh")
cur = conn.cursor() 			
cur.execute("select * from STUDENT")
info = cur.fetchall() 
print len(info)   	#获得表中有多少条数据
for ii in info:
    print ii[0]+' '+ii[1]+' '+ii[2]+' '+ii[3].strftime('%Y-%m-%d')+' '+ii[4]	
cur.close()
conn.commit()
conn.close()


你可能感兴趣的:(ubuntu下ODBC访问mssql和sybase(perl&python))