14
14

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で操作するスクリプト

Last updated at Posted at 2013-07-11

genのインストール

gem install mysql
gem list

gem listruby-mysqlが入っていればインストール成功

rubyのスクリプト作成

test.ruby
require 'rubygems'
require 'mysql'

my = Mysql::new("サーバー名(ipでも可)", "データベース名", "パスワード", "スキーマー名", ポート番号)
selectSql = "select id, name from table;"
res = my.query(selectSql)
res.each_hash do |row|
  id = row["id"]
  tel = row["name"]
  print "id:" + id + "name:" + name
end

ファイル名はtest.rubyなどrubyの拡張子を指定して作成

スクリプト実行

ruby test.ruby

これで結果が返ってくる

おまけ

電話番号を半角数字に正規化するプログラム

require 'rubygems'
require 'mysql'
require 'nkf'

deleteWordHan = Array["-",")","(","+"]

my = Mysql::new("192.XXX.XXX.XXX", "XXXXX", "XXXXXXXX", "XXXXX", 00000)
selectSql = "select id, tel from m_corporation;"

res = my.query(selectSql)
res.each_hash do |row|
  id = row["id"]
  tel = row["tel"]
  tel = NKF.nkf('-m0Z1 -w', tel)

  for var in deleteWordHan do
    tel = tel.delete(var)
  end

  updateSql = "update m_corporation set tel_normalized = '" + tel + "' where id = " + id + "" + "\n"
  print updateSql
  my.query(updateSql)

end

update文もselect文のときと同じようにかける。
全角文字を半角にするためにnkfを使っているがこれはgemのインストールは不要で使える。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?