0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLをRubyで操作する際のERROR (接続エラー)

Last updated at Posted at 2017-01-24

はじめに

RubyでMySQLに連続してinsertする際に、errorが発生する。

error内容

C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-mysql-2.9.14/lib/mysql/protocol.rb:153:in 
`initialize': Only one usage of each socket address (protocol/network address/port) is normally permitted.
 - connect(2) for "127.0.0.1" port 3306 (Errno::EADDRINUSE) from 
 - C:/Ruby22-64/lib/ruby/gems/2.2.0/gems/ruby-mysql-2.9.14/lib/mysql/protocol.rb:153:in `new' 
 - fromC:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-mysql-2.9.14/lib/mysql/protocol.rb:153:in 
 - `block in initialize'
        from C:/Ruby22-x64/lib/ruby/2.2.0/timeout.rb:73:in `timeout'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-mysql-.9.14/lib/mysql/protocol.rb:147:ininitialize'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-mysql-2.9.14/lib/mysql.rb:115:in `new'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-mysql-2.9.14/lib/mysql.rb:115:in `connect'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-mysql-2.9.14/lib/mysql.rb:50:in `new'
        from program.rb:201:in `insert'
        from program.rb:216:in `block in select_mysql'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-mysql-2.9.14/lib/mysql.rb:675:in `call'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/ruby-mysql-2.9.14/lib/mysql.rb:675:in `each'
        from program.rb:212:in `select_mysql'
        from program.rb:221:in `<main>'

errorの発生の原因

連続してデータベースにデータをinsertすると、接続できないタイミングが発生するらしい。
要するに、MySQLの3306番ポートに接続出来なかったためにエラーが発生する。

例えば以下のようなプログラム

insert.rb
require 'mysql'

for t in 0..10000000 do
  my = Mysql.new('127.0.0.1', 'root', 'pass', 'database_naem')
  #table_naem に 変数tの値を入れる
  res = my.query("insert into table_name values(#{t})")
  my.close
end

上のような記述だと、短期間で接続と切断を繰り返すので、
なんらかのタイミングで接続エラーを起こしてしまう場合がある。

改善策

接続エラーを発生させないためには、
for文の中で、接続と切断の記述をしない。

例えば以下のようにする

insert.rb
require 'mysql'

my = Mysql.new('127.0.0.1', 'root', 'pass', 'database_naem')

for t in 0..10000000 do
  res = my.query("insert into table_name values(#{t})")
end
my.close

このように、
for文の外で、接続と切断をすることで
接続エラーを回避することが出来る。

0
1
2

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?