linux系統下使用Python3 + freetds + unixODBC連線sybase
阿新 • • 發佈:2020-10-26
下載FreeTDS
wget -c http://ibiblio.org/pub/Linux/ALPHA/freetds/stable/freetds-stable.tgz
安裝
$:tar zxvf freetds-stable.tgz
$:cd freetds-0.91/
$:./configure --prefix=/usr/local/freetds --with-unixodbc=/usr/ --with-tdsver=5.0
$:make && make install
配置
$:vim /usr/local/freetds/etc/freetds.conf #新增如下內容: [MYSYBASE] host = IP 地址 port = 埠號 tds version = 5.0 client charset = UTF-8 #[]內填寫自己需要連線的例項名,host和port填寫自己服務的ip和埠
測試連線
$:/usr/local/freetds/bin/tsql -S MYSYBASE -U 使用者名稱 -P 密碼
#如果出現如下內容,或者類似內容,表示連線成功,此時可以執行一些SQL語句試試
locale is "en_US.utf8"
locale charset is "UTF-8"
using default charset "UTF-8"
1>
下載unixODBC
$:wget -c ftp://ftp.unixodbc.org/pub/unixODBC/unixODBC-2.3.0.tar.gz
安裝
$tar zxvf unixODBC-2.3.2.tar.gz $cd unixODBC-2.3.2 $./configure $make && make install
配置
#建立驅動的模板檔案1.txt 內容如下: [TDS] Description = Sybase Setup = /usr/lib/libtdsS.so Driver64 = /usr/local/freetds/lib/libtdsodbc.so Driver = /usr/local/freetds/lib/libtdsodbc.so setup64 = /usr/lib64/libtdsS.so FileUsage = 1 UsageCount = 2 #然後使用odbcinst安裝驅動: odbcinst -i -d -f 1.txt # 出現以下內容: odbcinst: Driver installed. Usage count increased to 1. Target directory is /etc # 可以檢查一下/etc/odbcinst.ini,如果可以看到TDS的內容,說明配置沒問題 #也可以用odbcinst -q -d 檢查驅動
#建立資料來源的模板檔案,內容如下:
[MYSYBASE]
Driver = TDS
Descrption = Sybase Server
Trace = No
Server = IP地址
Database = 資料庫
Port = 埠號
#這裡的Database,IP地址和埠號替換成自己需要的即可
odbcinst -i -s -f 2.txt
#執行完成以後,會在使用者的home目錄下生成.odbc.ini的檔案,vim ~/.odbc.ini檢查一下檔案內容即可。也可以用odbcinst -q -s檢查 可用的資料來源
#用isql測試連線: isql -v MYSYBASE 使用者名稱 密碼
#如果出現如下內容,說明連線成功了。
+---------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------+
SQL>
-linux系統安裝pyodbc,pip安裝不上,報錯需要先安裝unixODBC和unixODBC-devel
sudo apt-get install unixodbc unixodbc-dev
-Python連線
import pyodbc
conn=pyodbc.connect("DSN=xiaosu;UID=uid;pwd=password")
cursor=conn.cursor()
#輸出資料庫中所有表名
cursor.execute("select name from sysobjects where type ='U'")
for i in cursor:
print(i)