ubuntu下ODBC訪問mssql和sybase(perl&python)

1、安裝freetdshtml

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

2、安裝unixodbcmysql

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

3、獲取DBD-ODBCshell

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

4、安裝測試

tar xzvf DBD-ODBC-1.52.tar.gz fetch

 cd DBD-ODBC-1.52/spa

 perl Makefile.PL -o /usr.net

make&sudo make install

5、配置(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

6、測試

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;

7、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()
相關文章
相關標籤/搜索