开发者

What is the difference between DBI and DBD?

Can someone please shed some light on what exactly is DBI and DBD? When sh开发者_运维知识库ould 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜