0

I'm using .count method in a mysql2 query results:

My code:

  require "mysql2"

  hostname='db.xxxxx.xxx'
  port='3306'
  username='xxxxxx'
  password='xxxxxxxxxxxxxxxxxxxxxxxxxx'
  database='xxx'

  dbh = Mysql2::Client.new(:host=> hostname, :username=> username, :password=> password, :database=> database, :port=> port.to_f, :database_timezone=> :utc, :application_timezone => :local)


  results=dbh.query("SELECT * FROM xxx")
    p results.count
    i=0
    results.each do |result|
        i=i+1   
    end

    p results.count

With the first results.count I obtain the number of SELECT results rows as expected. But for the second one, I obtain (sometimes!) a different value:


My results:

$ ruby test_count.rb
4942
4942

$ ruby test_count.rb 
4942
24773520

$ ruby test_count.rb 
4942
37442208

My config:

$ rvm --version
rvm 1.13.4 (stable) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]

$ ruby --version
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]

$ gem list

*** LOCAL GEMS ***

Ascii85 (1.0.1)
bundler (1.1.3)
curb (0.8.0)
mime-types (1.18)
mysql (2.8.1)
mysql2 (0.3.11)
pdf-reader (1.1.1)
prawn (0.12.0)
prawn-core (0.8.4)
rake (0.9.2.2)
ruby-filemagic (0.4.2)
ruby-rc4 (0.1.5)
rubygems-bundler (0.9.2)
RubyInline (3.11.2)
rvm (1.11.3.3)
ttfunk (1.0.3)
ZenTest (4.8.0)

Someone have any idea why is this happen?

Thanks

  • 2
    Sounds like result is being modified. Can you post the actual code? What you posted is syntactically invalid. – d11wtq Jun 11 '12 at 00:47
  • Thanks, I have updated my code. Runing this code give me the same results, sometimes I have the good answer, sometimes a big integer – user1447891 Jun 11 '12 at 17:39

1 Answers1

0

Check your = versus ==. Also, the first results is an array. If you change to a string by doing some sort of .to_s or join and putting it back in the same variable, eg, results = results.join, then length would change. If you add elements to the array by mistake using results += results + another_array, then your count will increas fast. Best is to post your real code here. I know because I have done some of these at one time or another.

Anil
  • 3,899
  • 1
  • 20
  • 28