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

New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3markstory
 
Intro To jQuery In Drupal
Intro To jQuery In DrupalIntro To jQuery In Drupal
Intro To jQuery In DrupalMatthew Farina
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionPhilip Norton
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
12. CodeIgniter vederea inregistrarilor2
12. CodeIgniter vederea inregistrarilor212. CodeIgniter vederea inregistrarilor2
12. CodeIgniter vederea inregistrarilor2Razvan Raducanu, PhD
 
Getting Into Drupal 8 Configuration
Getting Into Drupal 8 ConfigurationGetting Into Drupal 8 Configuration
Getting Into Drupal 8 ConfigurationPhilip Norton
 
Persistence patterns for containers
Persistence patterns for containersPersistence patterns for containers
Persistence patterns for containersStephen Watt
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
06 Php Mysql Connect Query
06 Php Mysql Connect Query06 Php Mysql Connect Query
06 Php Mysql Connect QueryGeshan Manandhar
 
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 APIAlexandru Badiu
 
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, 2018Balázs Tatár
 
13. CodeIgniter vederea inregistrarilor3
13. CodeIgniter vederea inregistrarilor313. CodeIgniter vederea inregistrarilor3
13. CodeIgniter vederea inregistrarilor3Razvan Raducanu, PhD
 

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

perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applicationsJoe Jiang
 
DBI Advanced Tutorial 2007
DBI Advanced Tutorial 2007DBI Advanced Tutorial 2007
DBI Advanced Tutorial 2007Tim Bunce
 
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::ClassDave Cross
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in PerlLaurent Dami
 
Introducing Modern Perl
Introducing Modern PerlIntroducing Modern Perl
Introducing Modern PerlDave Cross
 
Efficient Shared Data in Perl
Efficient Shared Data in PerlEfficient Shared Data in Perl
Efficient Shared Data in PerlPerrin Harkins
 

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

Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQLddiers
 
DBD::SQLite
DBD::SQLiteDBD::SQLite
DBD::SQLitecharsbar
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
DBIx::Class vs. DBix::DataModel
DBIx::Class vs. DBix::DataModelDBIx::Class vs. DBix::DataModel
DBIx::Class vs. DBix::DataModelLaurent Dami
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Serverhendrikvb
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 
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 designBITS
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8Alexei Gorobets
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friendkikoalonsob
 
DBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たちDBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たちRyo Miyake
 
[PHP] Zend_Db (Zend Framework)
[PHP] Zend_Db (Zend Framework)[PHP] Zend_Db (Zend Framework)
[PHP] Zend_Db (Zend Framework)Jun Shimizu
 
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 loggingTricode (part of Dept)
 

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 (Красимир Беров) (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

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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 organizationRadu Cotescu
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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 productivityPrincipled Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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 DevelopmentsTrustArc
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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 2024The Digital Insurer
 
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 2024Rafal Los
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Dernier (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

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