tags:

views:

434

answers:

5

Can someone please shed some light on what exactly is DBI and DBD? When should either one be used and the benefits of using one over the other.

+9  A: 

DBI is the interface. DBD are the implementations of that interface.

Paul Tomblin
Sort of. It's more like DBI is the external interface, and DBD is the internal interface. DBD doesn't know about DBI (theoretically), and the user of DBI doesn't know about the DBD.
jrockway
+15  A: 

DBI is database access library, whereas DBDs are "drivers" which are used by DBI to access particular database (eg. there is one DBD for MySQL, another one for PostgreSQL etc). You should use DBI rather than DBDs directly.

el.pescado
+8  A: 

From the DBI docs:

             |<- Scope of DBI ->|
                  .-.   .--------------.   .-------------.
  .-------.       | |---| XYZ Driver   |---| XYZ Engine  |
  | Perl  |       | |   `--------------'   `-------------'
  | script|  |A|  |D|   .--------------.   .-------------.
  | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine|
  | DBI   |  |I|  |I|   `--------------'   `-------------'
  | API   |       | |...
  |methods|       | |... Other drivers
  `-------'       | |...
                  `-'

The boxes labeled XYZ driver and Oracle driver are DBD modules.

So your code talks to DBI. DBI talks to the appropriate DBD module for your database. The DBD module talks to your database. This results in a single, consistent interface to different databases.

friedo
+1  A: 

Use them together. For example, with MySQL:

use DBI;

$dsn = "DBI:mysql:database=$database;host=$hostname;port=$port";
$dbh = DBI->connect($dsn, $user, $password);

$sth = $dbh->prepare("SELECT * FROM foo WHERE bla");
$sth->execute;

If instead you're talking to an Oracle database, you may be able to get away with changing only the $data_source argument to DBI::connect:

$dbh = DBI->connect("dbi:Oracle:host=$host;sid=$sid", $user, $password);
Greg Bacon
+3  A: 

DBI stands for database interface. DBD stands for database driver.

As a programmer you should always use the interface (DBI). The interface, in turn, uses the driver. The reason to use DBI instead of using DBD directly is that it provides a consistent abstraction layer for working with databases. There are many DBD modules but you only need to learn one interface. Additionally, this makes it relatively easy to change the database your application uses by simply changing the driver. The interface is the same. (The query syntax might be a little different.)

Michael Carman
+1 for the good concise definition.
Axeman