LoginSignup
5
5

More than 5 years have passed since last update.

RubyでSQL Serverに接続する(TinyTDS)

Last updated at Posted at 2017-11-10

RubyからSQLServerに接続する方法です。
TinyTDSを使います

Ruby Driver for SQL Server
https://docs.microsoft.com/ja-jp/sql/connect/ruby/ruby-driver-for-sql-server

前提条件

  • Ruby2.3.3p222を使用します。
  • path等は自分の環境で適宜読み替えて下さい。
  • Windows 10 環境で確認しました。
  • CentOS 7.4 環境で確認しました。
  • Debian環境では確認していません。

環境構築

Windows

Ruby+Devkitのインストール

RubyInstallerを使いインストールします。
https://rubyinstaller.org/downloads/
参考:WindowsにRubyをインストールする(初心者向け)

uruのインストール

uruを使ってバージョン管理をします。1

  1. https://bitbucket.org/jonforums/uru/wiki/Downloads からuru-0.8.4-windows-x86をダウンロード
  2. ダウンロードしたuruをC:\Ruby\tools\uruへ解凍
  3. 以下コマンドにてインストール
cd C:\Ruby\tools\uru
uru_rt admin install

Rubyバージョン切り替え

uru admin add C:\Ruby\Ruby23-x64\bin
uru 233p222

参考:pikの替わりにuru~windowsで複数バージョンのrubyを切り替える~

Linux

rbenvのインストール

rbenvを使ってバージョン管理をします。1
参考:rbenvを用いたruby環境構築手順(CentOS7.1)
参考:rbenv で ruby の環境を整える

Rubyのインストール

rbenv install 2.3.3

FreeTDSのインストール

  • Debian
    sudo apt install freetds-common freetds-bin
  • RHEL
    yum install -y freetds freetds-devel

Windows・Linux共通

bundlerのインストール

bundlerを使ってgemの管理をします。1
gem install bundler

TinyTDSのインストール

  • Gemfileの作成
    bundle init
  • Gemfileに追記
    gem 'tiny_tds'
  • インストール
    bundle install --path vendor/bundle

使い方

SELECT文サンプル

test.rb
require 'rubygems' #bundlerを使わない場合
require 'bundler/setup' #bundlerを使う場合
require 'tiny_tds'

client = TinyTds::Client.new username: '<user>', password: '<pass>', host: '<target_host>', port: 1433, database: '<db_name>', azure: false

results = client.execute 'SELECT * FROM <table_name>'

results.each do |row|
  puts row['<column_name>']
end

実行結果

# ruby test.rb
<column_data>
<column_data>
<column_data>
<column_data>
...

メモ

  • port: 1433は省略可能
  • azure: falseもfalseなら省略可能
  • CentOS 7.4環境で実行すると警告warning: TinyTds: :use_utf16 option not supported in this version of FreeTDS.が発生する。use_utf16: falseにしてもダメ

  1. しなくてもいいけど、したほうがいい 

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5