From: Brian Candler Date: 2011-01-02T05:10:58+09:00 Subject: Re: write right method to be concise Pen Ttt wrote in post #971751: > there is a section of my program,it can run, > require 'mysql' > dbh = Mysql.real_connect("localhost", "root", "222222") > days.times do #days=10000 > case code > when "hk" then > str="use dzh_hk" > dbh.query(str) > str_insert="insert into quote (code,date,price)values (?,?,?) > st=dbh.prepare(str_insert) > st.execute(data[0],data[1],data[2]) > when "sh" then > str="use dzh_sk" > dbh.query(str) > str_insert="insert into quote (code,date,price)values (?,?,?) > st=dbh.prepare(str_insert) > st.execute(data[0],data[1],data[2]) > when "sz" then > str="use dzh_sz" > dbh.query(str) > str_insert="insert into quote (code,date,price)values (?,?,?) > st=dbh.prepare(str_insert) > st.execute(data[0],data[1],data[2]) > end > end > #others ommitted > i feel it's burdensome,want to make it be concise, i writ a method > in my program > > p1: > require 'mysql' > days.times do > def myinsert(code,data) > dbh = Mysql.real_connect("localhost", "root", "222222") > str="use dzh_"+code > dbh.query(str) > str_insert="insert into quote (code,date,price)values (?,?,?) > st=dbh.prepare(str_insert) > st.execute(data[0],data[1],data[2]) > end > end > #others ommitted > Mysql::Error: Too many connections > > p2: > require 'mysql' > dbh = Mysql.real_connect("localhost", "root", "222222") > days.times do > def myinsert(code,data) > str="use dzh_"+code > dbh.query(str) > str_insert="insert into quote (code,date,price)values (?,?,?) > st=dbh.prepare(str_insert) > st.execute(data[0],data[1],data[2]) > end > end > #others ommitted > NameError: undefined local variable or method `dbh' for main:Object > > would you mind tell me to write a right method to make it be concise? You have several choices: 1. Pass dbh as an extra parameter to myinsert() 2. Make a wrapper class which holds the handle class SqlHelper def initialize(dbh) @dbh = dbh end def myinsert(code,data) @dbh.query("use dhz_#{code}") ... etc end end sql = SqlHelper.new(dbh) sql.myinsert(code, data) 3. Use a global variable ($dbh) to hold your database handle. This is probably OK for a short script, but is poor practice when building a large program. -- Posted via http://www.ruby-forum.com/.