简体   繁体   中英

What is the difference between DBI and DBD?

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 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.

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

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.)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM