おっさんエンジニアの忘備録

Linux系の各種作業を自分用の忘備録として残しています

【Ruby】ruby-mysqlを使用してMySQLに接続

事前にやっておくこと

# gem install ruby-mysql

ruby-mysqlを入れておく必要があります。

環境

RHEL6.7
ruby2.3.0p0
MySQL5.7.12

使用するテーブル

以下のzaikoテーブルを使用します

mysql> SHOW COLUMNS FROM zaiko;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| maker | text | YES | | NULL | |
| type | text | YES | | NULL | |
| serial | varchar(100) | YES | | NULL | |
| purpose | varchar(20) | YES | | NULL | |
| input_date | date | YES | | NULL | |
| output_date | date | YES | | NULL | |

mysql> select * from zaiko;
+----+--------+-------+--------+----------+------------+-------------+
| id | maker  | type  | serial | purpose  | input_date | output_date |
+----+--------+-------+--------+----------+------------+-------------+
|  2 | maker1 | type1 | 001    | purpose1 | 2016-04-01 | 2016-04-02  |
|  3 | maker2 | type2 | 002    | purpose2 | 2016-04-03 | 2016-04-04  |
|  4 | maker3 | type3 | 003    | purpose3 | 2016-04-03 | 2016-04-04  |
|  5 | maker4 | type4 | 004    | purpose4 | 2016-04-05 | 2016-04-06  |
|  6 | maker5 | type5 | 005    | purpose5 | 2016-04-06 | 2016-04-07  |
+----+--------+-------+--------+----------+------------+-------------+
5 rows in set (0.01 sec)

簡単なSELECT

◆ソース(mysql_select.rb)

require 'mysql'

# DBに接続
my = Mysql::new("127.0.0.1", "[ユーザ名]", "[パスワード]", "[DB名]")

# 抽出結果でループ
result = my.query("select maker,type,serial,purpose,\
input_date,output_date from zaiko").each do \
|maker,type,serial,purpose,input_date,output_date|

    # レコードの内容を出力
    puts "#{maker},#{type},#{serial},#{purpose},#{input_date},#{output_date}"
end

# DBの切断
my.close

◆実行結果

# ruby mysql_select.rb
maker1,type1,001,purpose1,2016-04-01,2016-04-02
maker2,type2,002,purpose2,2016-04-03,2016-04-04
maker3,type3,003,purpose3,2016-04-03,2016-04-04
maker4,type4,004,purpose4,2016-04-05,2016-04-06
maker5,type5,005,purpose5,2016-04-06,2016-04-07

パラメータを持つSELECT

◆ソース(mysql_select2.rb)

require 'mysql'

# DBに接続
my = Mysql::new("127.0.0.1", "root", "Ph/*CyFUf0gt", "test_db")

# SQLの作成
stmt = my.prepare("select maker,type,serial,purpose,input_date,\
                   output_date from zaiko where serial = ?")

# SQLの実行&レコードの取り出し
tuple = stmt.execute('001').fetch       # 結果はtupleに配列で格納される

# レコードが存在した場合は結果を出力
if tuple then
    puts "#{tuple[0]},#{tuple[1]},#{tuple[2]},#{tuple[3]},#{tuple[4]},#{tuple[5]}"
end

# DBの切断
my.close

◆実行結果

# ruby mysql_select2.rb
maker1,type1,001,purpose1,2016-04-01,2016-04-02

INSERT

◆ソース(mysql_insert.rb)

require 'mysql'

# DBに接続
my = Mysql::new("127.0.0.1", "root", "Ph/*CyFUf0gt", "test_db")

# SQLの作成
stmt = my.prepare("insert into zaiko(maker,type,serial,purpose,input_date,output_date) \
                   values(?,?,?,?,?,?)")

# SQLの実行
stmt.execute('maker6','type1','006','purpose6','2016-04-08','2016-04-09')

# DBの切断
my.close

mysql_insert.rb実行後のselect実行結果

mysql> select * from zaiko;
+----+--------+-------+--------+----------+------------+-------------+
| id | maker  | type  | serial | purpose  | input_date | output_date |
+----+--------+-------+--------+----------+------------+-------------+
|  2 | maker1 | type1 | 001    | purpose1 | 2016-04-01 | 2016-04-02  |
|  3 | maker2 | type2 | 002    | purpose2 | 2016-04-03 | 2016-04-04  |
|  4 | maker3 | type3 | 003    | purpose3 | 2016-04-03 | 2016-04-04  |
|  5 | maker4 | type4 | 004    | purpose4 | 2016-04-05 | 2016-04-06  |
|  6 | maker5 | type5 | 005    | purpose5 | 2016-04-06 | 2016-04-07  |
|  7 | maker6 | type1 | 006    | purpose6 | 2016-04-08 | 2016-04-09  |
+----+--------+-------+--------+----------+------------+-------------+
6 rows in set (0.00 sec)
idが7の行が追加されています

UPDATE

◆ソース(mysql_update.rb)

require 'mysql'

# DBに接続
my = Mysql::new("127.0.0.1", "root", "Ph/*CyFUf0gt", "test_db")

# SQLの作成
stmt = my.prepare("update zaiko set maker=? where serial=?")

# SQLの実行
stmt.execute('changed1','001')

# DBの切断
my.close

mysql_update.rb実行前のselect実行結果

mysql> select * from zaiko;
+----+--------+-------+--------+----------+------------+-------------+
| id | maker  | type  | serial | purpose  | input_date | output_date |
+----+--------+-------+--------+----------+------------+-------------+
|  2 | maker1 | type1 | 001    | purpose1 | 2016-04-01 | 2016-04-02  |
|  3 | maker2 | type2 | 002    | purpose2 | 2016-04-03 | 2016-04-04  |
|  4 | maker3 | type3 | 003    | purpose3 | 2016-04-03 | 2016-04-04  |
|  5 | maker4 | type4 | 004    | purpose4 | 2016-04-05 | 2016-04-06  |
|  6 | maker5 | type5 | 005    | purpose5 | 2016-04-06 | 2016-04-07  |
|  7 | maker6 | type1 | 006    | purpose6 | 2016-04-08 | 2016-04-09  |
+----+--------+-------+--------+----------+------------+-------------+
6 rows in set (0.00 sec)
今回作成したプログラムではserialが「001」のレコードのmakerを「type1」から「changed1」に変更します

mysql_update.rb実行後のselect実行結果

mysql> select * from zaiko;
+----+----------+-------+--------+----------+------------+-------------+
| id | maker    | type  | serial | purpose  | input_date | output_date |
+----+----------+-------+--------+----------+------------+-------------+
|  2 | changed1 | type1 | 001    | purpose1 | 2016-04-01 | 2016-04-02  |
|  3 | maker2   | type2 | 002    | purpose2 | 2016-04-03 | 2016-04-04  |
|  4 | maker3   | type3 | 003    | purpose3 | 2016-04-03 | 2016-04-04  |
|  5 | maker4   | type4 | 004    | purpose4 | 2016-04-05 | 2016-04-06  |
|  6 | maker5   | type5 | 005    | purpose5 | 2016-04-06 | 2016-04-07  |
|  7 | maker6   | type1 | 006    | purpose6 | 2016-04-08 | 2016-04-09  |
+----+----------+-------+--------+----------+------------+-------------+
6 rows in set (0.00 sec)
serialが「001」のレコードのmakerが「type1」から「changed1」に変更されています

DELETE

◆ソース(mysql_delete.rb)

require 'mysql'

# DBに接続
my = Mysql::new("127.0.0.1", "root", "Ph/*CyFUf0gt", "test_db")

# SQLの作成
stmt = my.prepare("delete from zaiko where serial=?")

# SQLの実行
stmt.execute('006')

# DBの切断
my.close

mysql_delete.rb実行前のselect実行結果

mysql> select * from zaiko;
+----+----------+-------+--------+----------+------------+-------------+
| id | maker    | type  | serial | purpose  | input_date | output_date |
+----+----------+-------+--------+----------+------------+-------------+
|  2 | changed1 | type1 | 001    | purpose1 | 2016-04-01 | 2016-04-02  |
|  3 | maker2   | type2 | 002    | purpose2 | 2016-04-03 | 2016-04-04  |
|  4 | maker3   | type3 | 003    | purpose3 | 2016-04-03 | 2016-04-04  |
|  5 | maker4   | type4 | 004    | purpose4 | 2016-04-05 | 2016-04-06  |
|  6 | maker5   | type5 | 005    | purpose5 | 2016-04-06 | 2016-04-07  |
|  7 | maker6   | type1 | 006    | purpose6 | 2016-04-08 | 2016-04-09  |
+----+----------+-------+--------+----------+------------+-------------+
6 rows in set (0.00 sec)
今回作成したプログラムではserialが「006」のレコードを削除します

mysql_delete.rb実行後のselect実行結果

mysql> select * from zaiko;
+----+----------+-------+--------+----------+------------+-------------+
| id | maker    | type  | serial | purpose  | input_date | output_date |
+----+----------+-------+--------+----------+------------+-------------+
|  2 | changed1 | type1 | 001    | purpose1 | 2016-04-01 | 2016-04-02  |
|  3 | maker2   | type2 | 002    | purpose2 | 2016-04-03 | 2016-04-04  |
|  4 | maker3   | type3 | 003    | purpose3 | 2016-04-03 | 2016-04-04  |
|  5 | maker4   | type4 | 004    | purpose4 | 2016-04-05 | 2016-04-06  |
|  6 | maker5   | type5 | 005    | purpose5 | 2016-04-06 | 2016-04-07  |
+----+----------+-------+--------+----------+------------+-------------+
5 rows in set (0.01 sec)
serialが「006」のレコードが削除されています

【Linux】システム関連コマンドリンク集

自分でブログを書こうとしたんですが、既に素晴らしいブログを公開されている方がたくさんいらっしゃるので、リンク集にしようかと思いますw

 

(1)topコマンド

qiita.com

orebibou.com

topコマンドの使い方・見方 | WEBサービス創造記

 

 

(2)freeコマンド

www.softel.co.jp

free コマンド 実行結果の見かた

 

 

(3)psコマンド

www.uetyi.com

codezine.jp

 

(4)iotop

www.agilegroup.co.jp

 

(5)逆引き

qiita.com

 

自分がハマったのは以下の2つです。

◆psコマンドがLinux/BSD系とSolarisで異なる

◆メモリ使用量の見方

メモリ使用量に関しては、

【top】

Mem: 12157736k total, 11839208k used, 318528k free, 160352k buffers
Swap: 6143992k total, 348992k used, 5795000k free, 10419328k cached

 

【free】

total used free shared buffers cached
Mem: 12157736 11831180 326556 140348 160360 10411948
-/+ buffers/cache: 1258872 10898864
Swap: 6143992 348992 5795000

 

・topコマンドのSwapの行に「10419328k cached」の表示があるので惑わされる

・usedが少ないのでメモリが足りないと勘違いする(実際はfreeコマンドの「-/+ buffers/cache: 1258872 10898864)がほぼ実体の使用量)

ってな感じでした。

 

(6)dstatコマンド

qiita.com

 

(7)sarコマンド

naoberry.com

【Ruby】メール送信

RubyのMailライブラリを使ってメールを送信するスクリプトを作ってみました。

github.com

 

事前にgem install mailでMailライブラリをインストールする必要があります。

 

◆ソース(mail_send.rb)

require 'mail'

mail = Mail.new do
    from 'satake@tsunagunet.com'
    to 'satake@tsunagunet.com'
    subject 'This is a test email'
    body 'hoge'
end

mail.deliver!

簡単ですね! bodyのところはファイルを指定することもできるみたいです。

【Ruby】RubyでPING

rubyでnet-pingを使ってPINGを確認するサンプルスクリプトを作ってみました。

事前に「gem install net-ping」でnet-pingをインストールする必要があります。

 

◆ソース(ping_check.rb)

require 'net/ping'

# PING送信先の指定
addr = 'yahoo.co.jp'

# インスタンス生成
pi = Net::Ping::External.new(addr);

# PINGチェック
if pi.ping?
    puts 'PING OK'
else
    puts 'PING NG'
end

 

◆実行結果

# ruby ping_check.rb
PING OK

【Ruby】Regexp(パターンマッチ)

先日、ファイル入出力の記事を書かせていただきましたが、そのファイルを使ってパターンマッチ処理もちょっとやってみようと思います。

 

◆jleague.txt

 

◆ソース(regexp.rb)

File.open 'jleague.txt' do |f|
    f.each_line do |line|
        if line =~ /(鹿島)アントラーズ/
            puts $1                                    
        end
    end
end

 

◆実行結果

# ruby regexp.rb jleague.txt
鹿島

 

とりあえず非常に簡単なパターンをやってみましたが、やり方がはPerlとほぼ変わらない感じっぽいですね。

もう少し難しいパターンも徐々にやっていきたいと思います。

RHEL6にVagrant(CentOS6.7)をインストール

qiita.com

こちらのサイトを参考にさせていただきました。

 

(1)DKMSインストール

カーネルモジュールのビルドとアップデートを助けるフレームワークのようで、カーネルをアップデートしてもViurualBoxのカーネルモジュールも自動的にアップデートされるみたいです。

# yum --enablerepo rpmforge install dkms

⇒あ、rpmforgeつかってます

 

(2)VirtualBoxのインストール

①専用のリポジトリ追加

# cd /etc/yum.repos.d
# wget http://download.virtualbox.org/virtualbox/rpm/rhel/virtualbox.repo
# yum --enablerepo=virtualbox list | grep VirtualBox
VirtualBox-3.2.x86_64 3.2.28_100435_el6-1 virtualbox
VirtualBox-4.0.x86_64 4.0.36_104075_el6-1 virtualbox
VirtualBox-4.1.x86_64 4.1.44_104071_el6-1 virtualbox
VirtualBox-4.2.x86_64 4.2.36_104064_el6-1 virtualbox
VirtualBox-4.3.x86_64 4.3.36_105129_el6-1 virtualbox
VirtualBox-5.0.x86_64 5.0.18_106667_el6-1 virtualbox

 

②5.0をインストールしてみる

# yum --enablerepo=virtualbox install VirtualBox-5.0

 

③rootをvboxusers グループに追加

# usermod -a -G vboxusers root

 

 

(3)Vagrantインストール

 

 

(4)Vagrantセットアップ
centos用のボックスを追加

# vagrant box add centos67 https://github.com/CommanderK5/packer-centos-template/releases/download/0.6.7/vagrant-centos-6.7.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'centos67' (v0) for provider:
box: Downloading: https://github.com/CommanderK5/packer-centos-template/releases/download/0.6.7/vagrant-centos-6.7.box
==> box: Successfully added box 'centos67' (v0) for 'virtualbox'!

⇒/root/.vagrant.d/boxes/centos67ディレクトリが作成されます

 

②適当にディレクトリ作成して移動

# cd /root/vagrant/centos67

 

③仮想化環境初期化

# vagrant init centos67
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.


Vagrant起動

# vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos67'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: centos67_default_1461121012287_41932
==> default: Fixed port collision for 22 => 2222. Now on port 2200.
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 (guest) => 2200 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2200
default: SSH username: vagrant
default: SSH auth method: private key
default:
default: Vagrant insecure key detected. Vagrant will automatically replace
default: this with a newly generated keypair for better security.
default:
default: Inserting generated public key within guest...
default: Removing insecure key from the guest if it's present...
default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
default: The guest additions on this VM do not match the installed version of
default: VirtualBox! In most cases this is fine, but in rare cases it can
default: prevent things such as shared folders from working properly. If you see
default: shared folder errors, please make sure the guest additions within the
default: virtual machine match the version of VirtualBox you have installed on
default: your host and reload your VM.
default:
default: Guest Additions Version: 4.3.30
default: VirtualBox Version: 5.0
==> default: Mounting shared folders...
default: /vagrant => /root/vagrant/centos67

 

⑤ログインしてみる

# vagrant ssh
[vagrant@localhost ~]$ cat /etc/redhat-release
CentOS release 6.7 (Final)
[vagrant@localhost ~]$ su -
パスワード:
[root@localhost ~]#

⇒初期パスワードはvagrantです

 

【Ruby】ハッシュ

この辺もperlでよく使っていたので。。。

 

(1)単純なパターン

①ソース(hash.rb)

hash = Hash.new()                # ハッシュの初期化

hash[:apple] = 1                    # 要素の挿入
hash[:orange] = 2
hash[:grape] = 3

puts hash[:apple]                    # keyを指定してvalueを取り出し

puts '----------------'

hash.each do |key,val|           # keyとvalueを順番に取り出し
    puts "#{key}: #{val}"
end

hash[:strawberry] = 4;           # ハッシュに要素を追加

puts '----------------'

hash.each do |key,val|          #再度keyとvalueを順番に取り出し 
    puts "#{key}: #{val}"
end

 

②実行結果

# ruby hash.rb
1
----------------
apple: 1
orange: 2
grape: 3
----------------
apple: 1
orange: 2
grape: 3
strawberry: 4

 

 

(2)ネストしたハッシュ

①ソース(hash_nest.rb)

hash = Hash.new { |hash,key| hash[key] = Hash.new {} }           # ハッシュの初期化

hash[:apple][:count] = 2;                                                              # 要素の挿入
hash[:apple][:price] = 50;
hash[:orange][:count] = 5;
hash[:orange][:price] = 100;
hash[:grape][:count] = 10;
hash[:grape][:price] = 30;

puts hash                                       # とりあえず出力

puts '----------------'
hash.each do |key,arr|                                 #各要素を取り出し
    arr.each do |item,value|
        puts "#{key}: #{item},#{value}"
    end
end

hash[:strawberry][:count] = 4;                   # 要素を追加
hash[:strawberry][:price] = 200;

puts '----------------'
puts hash


puts '----------------'
hash.each do |key,arr|                        #再度各要素を取り出し
    arr.each do |item,value|
        puts "#{key}: #{item},#{value}"
    end
end

 

②実行結果

# ruby hash_nest.rb
{:apple=>{:count=>2, :price=>50}, :orange=>{:count=>5, :price=>100}, :grape=>{:count=>10, :price=>30}}
----------------
apple: count,2
apple: price,50
orange: count,5
orange: price,100
grape: count,10
grape: price,30
----------------
{:apple=>{:count=>2, :price=>50}, :orange=>{:count=>5, :price=>100}, :grape=>{:count=>10, :price=>30}, :strawberry=>{:count=>4, :price=>200}}
----------------
apple: count,2
apple: price,50
orange: count,5
orange: price,100
grape: count,10
grape: price,30
strawberry: count,4
strawberry: price,200

perlとかPHPだと特に意識しないでネストしたハッシュを定義できたんですが、rubyの場合はHash.newをやらないとエラーになっちゃうんですね^^;