LoginSignup
3
3

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-11-11

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

TinyTDSのみの接続はこちら

環境構築

こちらを参照

Gemのインストール

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

SQLServer2008以前に接続する場合、gemのバージョンを落とす必要がある。
gem 'activerecord-sqlserver-adapter', '~>4.1.0'

使い方

SELECT文サンプル

database.yml
development:
  adapter:  "sqlserver"
  host:     "<host or ipaddress>"
  username: "<user id>"
  password: "<password>"
  database: "<db name>"  
test.rb
require 'rubygems' #bundlerを使わない場合
require 'bundler/setup' #bundlerを使う場合
require 'activerecord-sqlserver-adapter'

ActiveRecord::Base.configurations = YAML.load_file('database.yml')
ActiveRecord::Base.establish_connection(:development)

results = Record.all
results = Record.first
results = Record.find(1)
results = Record.where(Column1: 'hoge', Column2: 'fuga')

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

実行結果

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

直接SQLを書きたい

test.rb
require 'rubygems' #bundlerを使わない場合
require 'bundler/setup' #bundlerを使う場合
require 'activerecord-sqlserver-adapter'

ActiveRecord::Base.configurations = YAML.load_file('database.yml')
ActiveRecord::Base.establish_connection(:development)
con = ActiveRecord::Base.connection

# 結果を伴うクエリ実行
results = con.select_all("SELECT * FROM <TABLENAME>")

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

# 結果を伴わないクエリ実行
con.execute("UPDATE <TABLENAME> SET Column1 = #{'hoge'} WHERE id = 1")

参考

RubyからSQLServerのストアドを呼び出す
ActiveRecordで生SQLを使いたいときに便利なメソッド達

3
3
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
3
3