当前位置: 首页 > 工具软件 > ruby-odbc > 使用案例 >

linux下用ruby访问SQL SERVER数据库

宰父飞翼
2023-12-01
先安装 unixODBC
wget ftp://ftp.unixodbc.org/pub/unixODBC/unixODBC-2.3.0.tar.gz
./configure
make && make install
默认安装在 /usr/local/lib目录下
ini配置文件在 /usr/loca/etc 目录下

wget http://ibiblio.org/pub/Linux/ALPHA/freetds/stable/freetds-stable.tgz
./configure --with-unixodbc=/usr/local --with-tdsver=7.1 --with-gnutls --enable-msdblib
* 访问 Microsoft SQL Server 2008,需要 TDS protocol version = 7.1,[color=red]freetds新版本(0.91)已经去掉了7.2和8.0,最高只到7.1了,如果指定7.1以上版本,将使用默认的5.0版本[/color]
* 访问SQL Server 需要 Enable SSL using GnuTLS
*** redhat 需要 gnutls 和 gnutls-devel 包
make && make install
tsql -C
查看安装信息是否正确,如果不正确可以指定TDSVER进行连接测试
# TDSVER=7.1 tsql -H 192.168.5.7 -p 1433 -U sa

建立一个tds驱动文件模板: /usr/local/etc/tds.driver.template
[code]
[FreeTDS]
Description = v0.91 with protocol v7.1
Driver = /usr/local/lib/libtdsodbc.so
[/code]

注册tds驱动:
$ odbcinst -i -d -f tds.driver.template


在 odbc.ini 文件中配置 ODBC Data Source Names (DSN)
[code]
[DSN]
Driver = FreeTDS
Description = some Description
Trace = No
Server = <database server IP>
Port = <database server PORT>
Database = <Database_Name>
[/code]

范例:
[code]
[MS_PASSPORT]
Driver = FreeTDS
Description = MS passport connection via FreeTDS
Trace = No
Server = 192.168.7.5
Database = MS.Passport
Port = 1433

[MS_BLOG]
Driver = FreeTDS
Description = MS Blog connection via FreeTDS
Trace = No
Server = 192.168.7.5
Database = MS.Blog
Port = 1433
[/code]

测试通过:
# odbcinst --v
unixODBC 2.3.0
# odbcinst -q -d
[FreeTDS]
# odbcinst -q -s
[MS_PASSPORD]
[MS_BLOG]

# isql -v MS_BLOG sa msdn
+---------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------+
SQL> select top 10 * from [user]
...

连接查询成功

安装ruby包:
gem install ruby-odbc
gem install dbi
gem install dbd-odbc

测试:
irb
require 'rubygems'
require 'dbi'

dbh = DBI.connect('dbi:ODBC:MS_PASSPORT', 'sa', 'msdn')

dbh.select_all('select top 10 * from [user]'){|row| p row}

sth=dbh.prepare('select top 10 * from [user]')
sth.execute
while row=sth.fetch do
puts row
end

测试通过
 类似资料: