linux下用ruby访问SQL SERVER数据库

阅读更多
先安装 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, freetds新版本(0.91)已经去掉了7.2和8.0,最高只到7.1了,如果指定7.1以上版本,将使用默认的5.0版本
* 访问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
[FreeTDS]
Description     = v0.91 with protocol v7.1
Driver          = /usr/local/lib/libtdsodbc.so


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


在 odbc.ini 文件中配置 ODBC Data Source Names (DSN)
[DSN]
Driver  = FreeTDS 
Description     = some Description
Trace   = No 
Server      = 
Port      = 
Database        = 


范例:
[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


测试通过:
[root@redhat freetds-0.82]# odbcinst --v
unixODBC 2.3.0
[root@redhat freetds-0.82]# odbcinst -q -d
[FreeTDS]
[root@redhat freetds-0.82]# odbcinst -q -s
[MS_PASSPORD]
[MS_BLOG]

[root@redhat freetds-0.82]# 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

测试通过

你可能感兴趣的:(SQL,Server,Linux,SQL,Ruby,RedHat)