in reply to Re^2: dbi question
in thread dbi question

Is this connection object a separate object than DBI ?

DBI is a class, not an object. The connection object ($dbh) is an instance of the DBI class. They are not the same thing, but the DBI class defines how its instances behave.

Falling back on the standard analogy to animals, Dog - as in the concept of Dog, not a specific dog - is a class and your pet $fido is an instance of Dog. Dog and $fido are separate, but connected. You wouldn't say "$fido is Dog", but rather "$fido is a Dog".

In the same way, $dbh isn't DBI, but it is a DBI.

Does this connection object have a method prepare ?

Yes. The DBI class defines a prepare method, which is then available to all instances of the class. Going back to Dog and $fido, being able to bark is part of the definition of Dog, therefore, because $fido is a Dog, $fido can bark.

I am confused that , how can connection have a method ?

Well... That's a matter of abstraction, I'm afraid.

The connection object is not literally the database connection itself. It is an object which contains the connection, keeps track of the connection, and is used to represent the connection to allow for easier interaction with it. We do tend to talk about the connection object as if it were the actual connection, but it isn't, because that allows it to be much more flexible and easier to use, since we can do things like add methods to a connection object instead of having to deal directly with the raw data flowing between our programs and the databases they connect to.

Replies are listed 'Best First'.
Re^4: dbi question
by bart (Canon) on Feb 06, 2010 at 12:32 UTC
    The connection object ($dbh) is an instance of the DBI class.
    Technically, that's not exactly true, but in it pretty much behaves in that way. The class of $dbh is DBI::db.

    Why it is done this way, I don't really know. I guess that probably the idea was to restrict the number of methods $dbh has access to.

      Ah, right. Good catch. That's tripped me up a couple times when writing Moose classes with dbh attributes and I tried making them isa => 'DBI'. One of these days I'll remember about that without having to get it wrong first...