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.
DBI is the interface. DBD are the implementations of that interface.
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.
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.
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);
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.)