35
DBI: The Neophyte's Guide 1 What is DBI? • DBI = DataBase Interface • DBI is database-independent • DBI allows you to write code that interacts with databases independent of the underlying database • A DBI program will work with little, or no, modification on Oracle, Informix, MySQL and so on...

What is DBI?

  • Upload
    wells

  • View
    56

  • Download
    0

Embed Size (px)

DESCRIPTION

What is DBI?. DBI = D ata B ase I nterface DBI is database-independent DBI allows you to write code that interacts with databases independent of the underlying database A DBI program will work with little, or no, modification on Oracle, Informix, MySQL and so on. What are DBDs?. - PowerPoint PPT Presentation

Citation preview

Page 1: What is DBI?

DBI: The Neophyte's Guide 1

What is DBI?

• DBI = DataBase Interface

• DBI is database-independent

• DBI allows you to write code that interacts with databases independent of the underlying database

• A DBI program will work with little, or no, modification on Oracle, Informix, MySQL and so on...

Page 2: What is DBI?

DBI: The Neophyte's Guide 2

What are DBDs?

• DBD = DataBase Driver

• Drivers are used by DBI to perform the actual database work

• Drivers are database-dependent

• Drivers exist for most popular databases including Oracle, Informix, Ingres, mSQL, MySQL, Solid and many more

Page 3: What is DBI?

DBI: The Neophyte's Guide 3

Why do we need the DBI?

• Abstracted interface hides database-specific functionality from the programmer

• DBI scripts are generally completely portable between databases with little modification

• Faster application development and debugging cycle

Page 4: What is DBI?

DBI: The Neophyte's Guide 4

What about ODBC?• ODBC and DBI share similar goals and

heritage: platform- and database-independence

• DBI is far more compact and less complex than ODBC. ODBC has a richer feature set

• Although ODBC drivers exist for many operating systems, they can be expensive and difficult to use. DBI is free and easy to configure and use

• A driver called DBD::ODBC exists and can be used to connect to ODBC-based databases such as Microsoft Access

Page 5: What is DBI?

DBI: The Neophyte's Guide 5

DBI Resources

• The DBI home page– http://www.symbolstone.org/technology/perl/DBI

• ``Programming the Perl DBI’’ -- Alligator Descartes and Tim Bunce. Can be ordered via amazon.com from the DBI home page

• This presentation and demonstration source code can be downloaded from the DBI home page

Page 6: What is DBI?

DBI: The Neophyte's Guide 6

DBI Architecture• Architectural Overview

• A Handy Reminder

• Handles– Driver Handles– Database Handles– Statement Handles

• Basic Database Operations– Connecting to the Database

• Data Sources

– Disconnecting from the Database

Page 7: What is DBI?

DBI: The Neophyte's Guide 7

Architectural Overview

Page 8: What is DBI?

DBI: The Neophyte's Guide 8

A Handy Reminder

• A tip to help you remember which modules do what in DBI

– DBI is DataBase Independent– DBD is DataBase Dependent

Page 9: What is DBI?

DBI: The Neophyte's Guide 9

Handles

• All operations in DBI are performed via– DBI module as a static method– Driver Handles– Database Handle instance method– Statement Handle instance method

• Driver Handles are not used explicitly by the programmer in scripts

Page 10: What is DBI?

DBI: The Neophyte's Guide 10

Driver Handles

• Driver Handles encapsulate a DBD

• There exists exactly one driver handle for each loaded DBD

• For example, a script using both MySQL and Oracle will have two instantiated driver handles

• Driver handles are never used directly in programs and are for internal use only by DBI

Page 11: What is DBI?

DBI: The Neophyte's Guide 11

Database Handles

• Database Handles encapsulate a single connection to a database

• Database handles are created via a driver handle for the desired database type. This is done via the DBI->connect() method $dbh = DBI->connect( … );

Page 12: What is DBI?

DBI: The Neophyte's Guide 12

Statement Handles

• Statement Handles encapsulate a statement to be issued to the database

• Statement handles are created via a database handle. That is, a statement is issued to the database represented by the database handle$sth = $dbh->prepare( “SELECT yadda FROM blah” );

• Statement handles also allow you to fetch data from the issued statement from the database

Page 13: What is DBI?

DBI: The Neophyte's Guide 13

Handle Naming Conventions

• Throughout the example code in this presentation and other DBI texts, you might see the following naming convention of variables– $drh = Driver Handle– $dbh = Database Handle– $sth = Statement Handle

Page 14: What is DBI?

DBI: The Neophyte's Guide 14

Starting Out with DBI

• Initializing the DBI

• Data Sources

• Checking Available Drivers

• Connecting to the Database

• Disconnecting from the Database

• Example

Page 15: What is DBI?

DBI: The Neophyte's Guide 15

Initializing the DBI

• DBI can be initialized very simply by adding

use DBI;

to your scripts

• DBI internally handles all driver loading automatically and DBDs should not normally be explicitly use’d or require’d in your scripts

Page 16: What is DBI?

DBI: The Neophyte's Guide 16

Data Sources

• In summary, Data Source specification is about the most non-portable aspect of DBI

• In reality, a well-written DBI script that uses standard SQL can be ported by simply changing the DSN in the DBI->connect() call

Page 17: What is DBI?

DBI: The Neophyte's Guide 17

Connecting to the Database• The very first database operation you must do!

• Use the DBI->connect()method

• For example

$dbh = DBI->connect( ‘dbi:Oracle:DEV’, ‘user’, ‘pass’ );

• That is, we minimally specify the Data Source Name of the database, a username and password

• If successful, this will return a valid database handle

Page 18: What is DBI?

DBI: The Neophyte's Guide 18

Disconnecting from the Database

• Once all work has been completed, you must disconnect from the database

• Frees any used database and system resources

• Achieved by calling disconnect() against a valid database handle. For example:

$dbh->disconnect();

Page 19: What is DBI?

DBI: The Neophyte's Guide 19

Example • This example connects to a single Oracle database called

DEV

#!/usr/bin/perl -w

### Load the DBI module

use DBI;

### Perform the connection using the Oracle driver

$dbh = DBI->connect( "dbi:Oracle:DEV", "username",

"password" )

or die "Can't connect to Oracle database: $DBI::errstr\n";

### Disconnect from the database

$dbh->disconnect();

exit;

Page 20: What is DBI?

DBI: The Neophyte's Guide 20

Example • This example demonstrates connecting to two

different databases of different types#!/usr/bin/perl -w

### Load the DBI module

use DBI;

### Perform the connection using the Oracle driver

$dbh1 = DBI->connect( "dbi:Oracle:DEV", "username", "password" )

or die "Can't connect to Oracle database: $DBI::errstr\n";

$dbh2 = DBI->connect( "dbi:mSQL:host:dbname:1114", "username", "password" )

or die "Can't connect to mSQL database: $DBI::errstr\n";

$dbh1->disconnect();

$dbh2->disconnect();

exit;

Page 21: What is DBI?

DBI: The Neophyte's Guide 21

Interacting with the Database• Simple Queries

– Preparing Statements– Executing Statements– Fetching Data

• Non-SELECT Statements

• Bind Values

• Optimizing $dbh->do()

Page 22: What is DBI?

DBI: The Neophyte's Guide 22

Simple Queries

• The process of retrieving data from the database is a 4-stage cycle– Preparing the statement– Executing the statement– Fetching the data– Finishing the statement

Page 23: What is DBI?

DBI: The Neophyte's Guide 23

Preparing the Statement• The $dbh->prepare( $statement ) method is

used

• This can mean different things depending on the underlying DBD used. Oracle will use this stage to send the statement to the database for parsing. However, mSQL does nothing here at all

• The SQL statement is simply a Perl string and therefore can be supplied as a literal string or as a variable holding a built on-the-fly statement

Page 24: What is DBI?

DBI: The Neophyte's Guide 24

Preparing the Statement ( cont. )

#!/usr/bin/perl -w

### Load the DBI module

use DBI;

### The database handle

$dbh = DBI->connect( "dbi:Oracle:DEV", "username", "password" );

### Prepare the statement handle

$sth = $dbh->prepare( "SELECT id, name FROM megaliths" );

...

exit;

Page 25: What is DBI?

DBI: The Neophyte's Guide 25

Executing the Statement

• Once the statement has been successfully prepared, it must be executed

• Depending on the database, this stage typically executes the prepared statement within the database and generates a result set ready for fetching

• Simply a case of calling $sth->execute() against your prepared statement handle

Page 26: What is DBI?

DBI: The Neophyte's Guide 26

Fetching the Data

• The fetch stage retrieves the data from the database row-by-row by use of a cursor

• The most commonly used fetch style is to retrieve the data as a Perl list via @row = $sth->fetchrow_array()

• You should continuously loop calling fetchrow_array() until all rows are returned

Page 27: What is DBI?

DBI: The Neophyte's Guide 27

Fetching Data - Example #/usr/bin/perl -w

### Load the DBI module

use DBI;

### Connect to the database

$dbh = DBI->connect( ‘dbi:Oracle:DEV’, ‘username’, ‘password’ );

### Prepare and execute the statement

$sth = $dbh->prepare( “SELECT name, type FROM megaliths” );

$sth->execute();

### Fetch the data

while ( @row = $sth->fetchrow_array() ) {

print "Megalith site $row[0] is a $row[1]\n";

}

### Disconnect from the database

$dbh->disconnect();

exit;

Page 28: What is DBI?

DBI: The Neophyte's Guide 28

Fetching the Data

• There are additional methods for fetching data from the statement handle:

fetchrow_arrayref()

fetchrow_hashref()

Page 29: What is DBI?

DBI: The Neophyte's Guide 29

Finishing the Statement

• DBI automatically marks the statement handles as inactive once all the data has been fetched from it

• You can manually mark statement handles as being inactive via the $sth->finish() method, but you should usually not need to invoke this method in your scripts

Page 30: What is DBI?

DBI: The Neophyte's Guide 30

Non-SELECT Statements

• Statements other than queries can be issued to the database via DBI

• For example, UPDATE, DELETE and INSERT statements

• These statements are issued by calling $dbh->do()

which combines preparation and execution in a single step

Page 31: What is DBI?

DBI: The Neophyte's Guide 31

Non-SELECT Statements ( cont. )

• For example:

$dbh->do( “DELETE FROM megaliths” );

$dbh->do( “DROP TABLE megaliths” );

$dbh->do( “INSERT INTO megaliths VALUES ( 1, ‘Stonehenge’,

‘Wiltshire’ )” );

Page 32: What is DBI?

DBI: The Neophyte's Guide 32

Bind Values

• A bind value is a value that can be bound to a placeholder declared within a SQL statement

• This is similar to creating an on-the-fly SQL statement such as:

$sth = $dbh->prepare( "

SELECT name, location

FROM megaliths

WHERE name = " . $dbh->quote( $siteName ) . "

" );

Page 33: What is DBI?

DBI: The Neophyte's Guide 33

Bind Values ( cont. )• However, instead of interpolating the generated

value into the SQL statement, you specify a placeholder and then bind the generated value to that

• For example:

$sth = $dbh->prepare( "

SELECT name, location

FROM megaliths

WHERE name = ?

" );

$sth->bind_param( 1, $dbh->quote( ‘Avebury’ ) );

Page 34: What is DBI?

DBI: The Neophyte's Guide 34

Optimizing $dbh->do()

• The default implementation of $dbh->do() calls prepare(), execute() and finish()for each invocation of $dbh->do()

• This can be optimized for repeated iterations by hand-preparing the statement but repeatedly executing the same statement handle

• This is very efficient when used with bind values

Page 35: What is DBI?

DBI: The Neophyte's Guide 35

Optimizing $dbh->do() ### Prepare the statement handle

$sth = $dbh->prepare( “DELETE FROM megaliths WHERE id = ?” );

### Remove the first 100 rows one-by-one...

$loopCounter = 0;

while ( $loopCounter < 100 ) {

$sth->execute( $loopCounter );

$loopCounter++;

}

$sth->finish();

...

• This is far faster than repeatedly preparing the same statement over and over again