linux使用pyodbc和freetds串連sqlserver

來源:互聯網
上載者:User

標籤:org   serve   style   install   編譯   free   gcc   驅動   運行   

安裝unixODBC

使用pyodbc需要Linux上安裝unixODBC

可使用yum或apt安裝unixODBC-devel包

編譯安裝:http://www.unixodbc.org/download.html

安裝成功驗證

#odbcinst -junixODBC 2.3.7DRIVERS............: /usr/local/etc/odbcinst.iniSYSTEM DATA SOURCES: /usr/local/etc/odbc.iniFILE DATA SOURCES..: /usr/local/etc/ODBCDataSourcesUSER DATA SOURCES..: /root/.odbc.iniSQLULEN Size.......: 8SQLLEN Size........: 8SQLSETPOSIROW Size.: 8

 

安裝串連驅動

unixodbc中沒有內建串連sqlserver的驅動,freetds提供了相關的串連驅動,也可以通過微軟提供的指令碼來安裝,這裡選擇freetds來提供串連驅動

微軟碟機動詳細https://docs.microsoft.com/zh-cn/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-2017

安裝freetds

https://github.com/FreeTDS/freetds

git或下載項目到檔案夾中

樣本使用freetds的0.91版本https://github.com/FreeTDS/freetds/releases/tag/branch-0_91

**安裝前確保安裝了如下工具:automake,autoconf,autogen,gettext,libtool,make,gcc,perl

解壓後進入目錄運行

./autogen.sh

make

make install

上述安裝針對github上的源碼安裝,下載其他包時有的已經產生了configure檔案只需運行./configure後make,make install。

預設安裝路徑為/user/local/etc

測試:編輯freetds.conf在其中加入sqlserver的串連資訊檔一般在/user/local/etc中

[server]  host = 192.168.6.6  port = 1433  tds version = 7.0  client chaeset = UTF-8

 

其中的tds version可查看檔案中的樣本選擇,錯誤的值可能導致串連失敗 Unexpected EOF from the server

使用tsql測試連接

#tsql -S server -U user -P passwordlocale is "en_US.UTF-8"locale charset is "UTF-8"using default charset "UTF-8"1>

 

安裝pyodbc

https://pypi.org/project/pyodbc/

pip install pyodbc或者下載包後進入主目錄python setup.py install

編輯/etc/odbcinst.conf檔案,該檔案也可能在/usr/local/etc中

添加freetds串連庫

在檔案中加入

[SQL Server]Driver          = /usr/local/lib/libtdsodbc.so

 

其中driver為freetds的提供的驅動檔案,SQL Server為連接字串使用的驅動名

 

測試:

import pyodbcDBCONNECTSTR = ‘DRIVER={SQL Server};SERVER=192.168.6.6;port=1433;DATABASE=test;UID=user;PWD=password;TDS_Version=7.0;‘conn=pyodbc.connect(DBCONNECTSTR)conn.close()

注意TDS_Version的值與/usr/local/etc/freetds.conf中的串連樣本一致

 

更多python串連sqlserver方法:

https://wiki.python.org/moin/SQL%20Server

https://www.cnblogs.com/AppleZhang/p/7878971.html

 

linux使用pyodbc和freetds串連sqlserver

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.