Db class and connection problems

Hello,

I am new in ruby and have a little problem… I have the following code

class Grid
attr_accessor :host

attr_accessor :connection

def initialize (host, user, passwd, dbname)
@host = host
@user = …
end

def connect
@connection = Mysql.real_connect(@host, @user, @passwd, @dbname)
if @connection then
puts “connected”
end
end

def query
res = @connection.query(“select * from table”)
return res
end
end

and now from a script

require “the clash file”

db = Grid.new(“localhost”,“user”,“password”,“db”)
db.connect
db.query

and I get an error cause the database seem to be closed… or which is
the same @connection is null? I only can make it work if I open and
close the database from inside the query method, but this query is
called more than 4000 times in the script and I reach the limit of
connections of my system’s TCP/IP

Anyone could help me? I don’t understand why I can share @host, @user
and the other attributes among the methods but @connection seems to be
lost.

thanks in advance.

Luis Moran wrote:

and I get an error

Show the exact error - I mean copy-paste it, including the backtrace.
Cross-reference backtrace entries which refer to your own code to the
actual lines of your source.

It would also be useful if you could give a complete small program which
replicates the problem, because it could just be a typo. At first glance
what you’ve written looks fine, but it’s not runnable - e.g. there’s no
require ‘mysql-ruby’ or require ‘ruby-mysql’. Also, it’s worth
mentioning which mysql library you’re using, and what version.

cause the database seem to be closed… or which is
the same @connection is null?

Those are two very different things. One says that @connection points to
some object, but the object says the database connection is closed (it
may have been closed due to some sort of error, for example). The other
says @connection points to nothing at all (well, technically an instance
of the ‘nil’ object), which could only happen if your own code set
@connection = nil.

I only can make it work if I open and
close the database from inside the query method, but this query is
called more than 4000 times in the script and I reach the limit of
connections of my system’s TCP/IP

If that’s true, then clearly you’re not closing each connection after
using it.

Regards,

Brian.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs