SlideShare une entreprise Scribd logo
1  sur  14
Télécharger pour lire hors ligne
Perl Programming
                 Course
            Working with databases




Krassimir Berov

I-can.eu
Contents
1. DBI
2. DBD
3. Connect
4. Select
5. Insert
6. Update
7. Delete
8. Example Application (CGI::Ex::Recipes)
DBI
• DBI - Database independent interface for
  Perl
  • Provides a consistent database interface,
    independent of the actual database being used
  • DBI is a layer of "glue" between an application
    and one or more database driver modules
  • DBI provides a standard interface and framework
    for the drivers to operate within
  • Most of the work is done by the drivers
DBI
• DBI Architecture
DBD::*
• Drivers provide implementations of the DBI
  methods using the private interface functions of
  the corresponding database engine
  • DBD::mysql – MySQL driver
  • DBD::SQLite – Self Contained RDBMS
  • DBD::Oracle - Oracle database driver
  • DBD::Pg - PostgreSQL database driver
  perl -MDBI -e'print join $/,DBI->available_drivers, $/'

  #many available on cpan...
  cpan[4]> i /^DBD::*/
Connect
• Establishes a database connection, or session, to
  the requested $data_source/$dsn.
• Returns a database handle object if the connection
  succeeds.
• Use $dbh->disconnect to terminate the connection.
• If the connect fails, it returns undef and sets both
  $DBI::err and $DBI::errstr.
  use DBI; use strict; use warnings;
  my $dsn = 'dbi:SQLite:dbname=$file';
  #or
  my $dsn = 'DBI:mysql:database=bgcc;host=localhost;';

  my $dbh = DBI->connect(
      $dsn, $username, $password
  ) or die $DBI::errstr;
Select
• Use Database Handle Methods and
  Statement Handle Methods
  to retrieve data in various forms

  use DBI; use strict; use warnings;
  #...
  my $sql = "SELECT * FROM recipes WHERE id = ?"
  my $sth = $dbh->prepare($sql);
  $sth->execute($id);
  my $hashref = $sth->fetchrow_hashref;
  my $arrayref = $sth->fetchrow_arrayref;
  my $arrayref = $sth->fetch;     # alias
  #or just
  my $arrayref = $dbh->selectrow_arrayref(
       $sql, %attr, @bind_values);
  my $hashref = $dbh->selectrow_hashref(
       $sql, %attr, @bind_values);
Insert
• Use prepare() and execute() to insert a
  row in a table

 use DBI; use strict; use warnings;
 #...
 my $sql = "INSERT INTO recipes
 (title, problem, analysis) VALUES (?, ?, ?)";
 $dbh->prepare($sql)->execute($title,$problem,$analysis);
Update
• Use prepare() and execute() or do() to
  update a row in a table
• The do() method can be used for non repeated non-
  SELECT statement (or with drivers that don't
  support placeholders)

  use DBI; use strict; use warnings;
  #...
  my $sql = "UPDATE recipes SET title=?, problem=?,
  analysis=? WHERE id=?";
  $true_or_undef = $dbh->prepare($sql)->execute(
     $title, $problem, $analysis, $id);

  $rows_affected = $dbh->do($sql_with_hardcoded_values);
Delete
• Use prepare() and execute() or do() to
  delete a row from a table



 use DBI; use strict; use warnings;
 #...
 my $sql = "DELETE FROM recipes WHERE id = ?";
 $dbh->prepare($sql)->execute($id);
 #or just
 $dbh->do($sql,undef,$id);
Example Application

#1.download and install Apache

#2.install CGI::Ex::Recipes within htdocs/
#with config option 'AllowOverride All'

cpan[1]> install CGI::Ex::Recipes
Example Application
DBI
• Ressources
  • Beginning Perl
    (Chapter 13 – Perl and databases
    (Introducing Relational Databases))
  • perldoc DBI
  • perldoc DBD::SQLite
  • perldoc DBD::mysql
  • etc...
Working with databases




Questions?

Contenu connexe

Tendances

Tendances (20)

New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 
Intro To jQuery In Drupal
Intro To jQuery In DrupalIntro To jQuery In Drupal
Intro To jQuery In Drupal
 
lab56_db
lab56_dblab56_db
lab56_db
 
Drupal Render API
Drupal Render APIDrupal Render API
Drupal Render API
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
12. CodeIgniter vederea inregistrarilor2
12. CodeIgniter vederea inregistrarilor212. CodeIgniter vederea inregistrarilor2
12. CodeIgniter vederea inregistrarilor2
 
Getting Into Drupal 8 Configuration
Getting Into Drupal 8 ConfigurationGetting Into Drupal 8 Configuration
Getting Into Drupal 8 Configuration
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
Persistence patterns for containers
Persistence patterns for containersPersistence patterns for containers
Persistence patterns for containers
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
06 Php Mysql Connect Query
06 Php Mysql Connect Query06 Php Mysql Connect Query
06 Php Mysql Connect Query
 
Learning the basics of the Drupal API
Learning the basics of the Drupal APILearning the basics of the Drupal API
Learning the basics of the Drupal API
 
Configuration resources
Configuration resourcesConfiguration resources
Configuration resources
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
 
13. CodeIgniter vederea inregistrarilor3
13. CodeIgniter vederea inregistrarilor313. CodeIgniter vederea inregistrarilor3
13. CodeIgniter vederea inregistrarilor3
 
Tax management-system
Tax management-systemTax management-system
Tax management-system
 

En vedette (7)

perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
DBI Advanced Tutorial 2007
DBI Advanced Tutorial 2007DBI Advanced Tutorial 2007
DBI Advanced Tutorial 2007
 
Database Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDatabase Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::Class
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
 
Introducing Modern Perl
Introducing Modern PerlIntroducing Modern Perl
Introducing Modern Perl
 
Efficient Shared Data in Perl
Efficient Shared Data in PerlEfficient Shared Data in Perl
Efficient Shared Data in Perl
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 

Similaire à Working with databases

DBIx::Class vs. DBix::DataModel
DBIx::Class vs. DBix::DataModelDBIx::Class vs. DBix::DataModel
DBIx::Class vs. DBix::DataModel
Laurent Dami
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
Alexei Gorobets
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friend
kikoalonsob
 

Similaire à Working with databases (20)

Sqlite perl
Sqlite perlSqlite perl
Sqlite perl
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
DBD::SQLite
DBD::SQLiteDBD::SQLite
DBD::SQLite
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
DBIx::Class vs. DBix::DataModel
DBIx::Class vs. DBix::DataModelDBIx::Class vs. DBix::DataModel
DBIx::Class vs. DBix::DataModel
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Server
 
About Data::ObjectDriver
About Data::ObjectDriverAbout Data::ObjectDriver
About Data::ObjectDriver
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
BITS: Introduction to relational databases and MySQL - Schema design
BITS: Introduction to relational databases and MySQL - Schema designBITS: Introduction to relational databases and MySQL - Schema design
BITS: Introduction to relational databases and MySQL - Schema design
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
 
fard car.pptx
fard car.pptxfard car.pptx
fard car.pptx
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friend
 
Advance Mobile Application Development class 01
Advance Mobile Application Development class 01Advance Mobile Application Development class 01
Advance Mobile Application Development class 01
 
DBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たちDBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たち
 
Php summary
Php summaryPhp summary
Php summary
 
[PHP] Zend_Db (Zend Framework)
[PHP] Zend_Db (Zend Framework)[PHP] Zend_Db (Zend Framework)
[PHP] Zend_Db (Zend Framework)
 
Intro to Drush
Intro to DrushIntro to Drush
Intro to Drush
 
Code Igniter 2
Code Igniter 2Code Igniter 2
Code Igniter 2
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Sql
SqlSql
Sql
 

Plus de Krasimir Berov (Красимир Беров)

Plus de Krasimir Berov (Красимир Беров) (15)

Хешове
ХешовеХешове
Хешове
 
Списъци и масиви
Списъци и масивиСписъци и масиви
Списъци и масиви
 
Скаларни типове данни
Скаларни типове данниСкаларни типове данни
Скаларни типове данни
 
Въведение в Perl
Въведение в PerlВъведение в Perl
Въведение в Perl
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
 
Network programming
Network programmingNetwork programming
Network programming
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
Subroutines
SubroutinesSubroutines
Subroutines
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Syntax
SyntaxSyntax
Syntax
 
Hashes
HashesHashes
Hashes
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Working with databases

  • 1. Perl Programming Course Working with databases Krassimir Berov I-can.eu
  • 2. Contents 1. DBI 2. DBD 3. Connect 4. Select 5. Insert 6. Update 7. Delete 8. Example Application (CGI::Ex::Recipes)
  • 3. DBI • DBI - Database independent interface for Perl • Provides a consistent database interface, independent of the actual database being used • DBI is a layer of "glue" between an application and one or more database driver modules • DBI provides a standard interface and framework for the drivers to operate within • Most of the work is done by the drivers
  • 5. DBD::* • Drivers provide implementations of the DBI methods using the private interface functions of the corresponding database engine • DBD::mysql – MySQL driver • DBD::SQLite – Self Contained RDBMS • DBD::Oracle - Oracle database driver • DBD::Pg - PostgreSQL database driver perl -MDBI -e'print join $/,DBI->available_drivers, $/' #many available on cpan... cpan[4]> i /^DBD::*/
  • 6. Connect • Establishes a database connection, or session, to the requested $data_source/$dsn. • Returns a database handle object if the connection succeeds. • Use $dbh->disconnect to terminate the connection. • If the connect fails, it returns undef and sets both $DBI::err and $DBI::errstr. use DBI; use strict; use warnings; my $dsn = 'dbi:SQLite:dbname=$file'; #or my $dsn = 'DBI:mysql:database=bgcc;host=localhost;'; my $dbh = DBI->connect( $dsn, $username, $password ) or die $DBI::errstr;
  • 7. Select • Use Database Handle Methods and Statement Handle Methods to retrieve data in various forms use DBI; use strict; use warnings; #... my $sql = "SELECT * FROM recipes WHERE id = ?" my $sth = $dbh->prepare($sql); $sth->execute($id); my $hashref = $sth->fetchrow_hashref; my $arrayref = $sth->fetchrow_arrayref; my $arrayref = $sth->fetch; # alias #or just my $arrayref = $dbh->selectrow_arrayref( $sql, %attr, @bind_values); my $hashref = $dbh->selectrow_hashref( $sql, %attr, @bind_values);
  • 8. Insert • Use prepare() and execute() to insert a row in a table use DBI; use strict; use warnings; #... my $sql = "INSERT INTO recipes (title, problem, analysis) VALUES (?, ?, ?)"; $dbh->prepare($sql)->execute($title,$problem,$analysis);
  • 9. Update • Use prepare() and execute() or do() to update a row in a table • The do() method can be used for non repeated non- SELECT statement (or with drivers that don't support placeholders) use DBI; use strict; use warnings; #... my $sql = "UPDATE recipes SET title=?, problem=?, analysis=? WHERE id=?"; $true_or_undef = $dbh->prepare($sql)->execute( $title, $problem, $analysis, $id); $rows_affected = $dbh->do($sql_with_hardcoded_values);
  • 10. Delete • Use prepare() and execute() or do() to delete a row from a table use DBI; use strict; use warnings; #... my $sql = "DELETE FROM recipes WHERE id = ?"; $dbh->prepare($sql)->execute($id); #or just $dbh->do($sql,undef,$id);
  • 11. Example Application #1.download and install Apache #2.install CGI::Ex::Recipes within htdocs/ #with config option 'AllowOverride All' cpan[1]> install CGI::Ex::Recipes
  • 13. DBI • Ressources • Beginning Perl (Chapter 13 – Perl and databases (Introducing Relational Databases)) • perldoc DBI • perldoc DBD::SQLite • perldoc DBD::mysql • etc...