前言
公司自研的CMDB系统连接了各种数据库,原来是在windows平台运行,后来迁移到Linux平台。结果除了MSSQL其他数据库都较轻易解决了。
环境准备
服务器:Linux CentOS
安装FreeTDS
安装unixODBC
步骤
- 配置freetds.conf,参考位置
/usr/local/freetds/etc
,可用locate freetds.conf
查找
# server specific section
[global]
# TDS protocol version
tds version = 7.2
# 防止中文乱码
client charset = UTF-8
# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
; dump file = /tmp/freetds.log
; debug flags = 0xffff
# Command and connection timeouts
; timeout = 10
; connect timeout = 10
# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.
# Try setting 'text size' to a more reasonable limit
text size = 64512
[MSSQL] # 对应odbc.ini中的Servername
host = hostname.database.chinacloudapi.cn
port = 1433
tds version = 7.2
- 配置odbcinst.ini,参考位置
/etc
,填写数据库驱动程序、数据库驱动安装程序,可用locate libtds
查找so文件
[FreeTDS] # 对应odbc.ini中的Driver
Description = FreeTDS Driver
Driver = /usr/local/freetds/lib/libtdsodbc.so
Setup = /usr/lib/libtdsS.so
UsageCount = 1
- 配置odbc.ini,参考位置在
/etc
[mssql_odbc] # 对应连接字符串中的DSN
Driver = FreeTDS # 对应odbcinst.ini中的[]
Servername = MSSQL # 对应freetds.conf中的[]
Database = xxx
- 在连接字符串中使用
MSSQL_URI = 'DSN=mssql_odbc;UID=username@host;PWD=xxxxx;CHARSET=utf8';
附录
- 参考上面的方式,ODBC+FreeTDS还可以连MySQL、Oracle等,总结起来就是绑定驱动文件、绑定数据库服务。
- Windows自带ODBC,不过类似linux需要额外手动加驱动使用的场合并不多
- 数据库驱动程序的列表
数据库 | 数据库驱动程序 | 数据库驱动安装程序 |
---|---|---|
TXT | libodbctxt.so | libodbctxtS.so |
NNTP | libnn.so | libodbcnnS.so |
MiniSQL | libodbcmini.so | libodbcminiS.so |
PostgreSQL | libodbcpsql.so | libodbcpsqlS.so |
MySQL | - | libodbcmyS.so |
Sybase/MS SQL | - | libtdsS.so |
Oracle | - | liboraodbcS.so |
unixODBC安装
yum install unixODBC
FreeTDS安装
- 下载FreeTDS安装包到服务器
wget -c xxxxx
- 解压
tar -zxvf freetds-stable.tgz
- 编译安装
- yum install gcc-c++
- yum install ncurses-devel
- cd freetds
- ./configure --prefix=/usr/local/freetds
- make && makeinstall
- 测试连接
tsql -H server -p port -U username -P password
- 查看信息
tsql -c
- 连接时修改tds版本号
TDSVER=xx tsql -H server -p port -U username -P password
- 修改全局TDS 版本号,freetds.conf修改[global]下面的tds version