perl programming - 04 programming database
Post on 15-Apr-2017
725 Views
Preview:
TRANSCRIPT
04 - Perl Programming
Database
156
Danairat T.
Line ID: Danairat
FB: Danairat Thanabodithammachari
+668-1559-1446
Danairat T.
Perl at the client Side
Perl and Database
• Perl uses the DBI (Database Interface) for DB integration
purpose. The DBI is database-independent, which means that
it can work with vendor specific DBD (Database Driver) for any
of database, such as Postgres, mySQL, Oracle, Sybase,
Informix, Access, ODBC, etc.
157
Perl Program DBI
DBD::Pg
DBD::Oracle
Postgres
Oracle
Danairat T.
Perl and Database - Topics
• Perl Modules for Database
• Prepare Database Environment (Postgres)
• Database Handler
• Database Statement
• Database Manipulation
– Select
– Add
– Update
– Delete
158
Danairat T.
Perl Modules for Database
159
• Query your existing modules using command line:-
• perl -MFile::Find=find -MFile::Spec::Functions -lwe 'find { wanted =>
sub { print canonpath $_ if /\.pm\z/ }, no_chdir => 1 },
• The DBI is normally located at
/usr/perl5/vendor_perl/5.8.4/i86pc-solaris-64int/
• The DBDs are normally located at
/usr/perl5/vendor_perl/5.8.4/i86pc-solaris-64int/DBD/
Danairat T.
Perl Modules for Database
160
• Install the Perl DBI:-
1. Download DBI module “DBI-1.58.tar.gz” from
www.cpan.org
2. Unzip as a directory and cd to the directory
gzip -cd DBI-1.58.tar.gz | tar xf -
3. Run standard perl module installationi. perl Makefile.PL
ii. make
iii. make test
iv. make install
4. Finished.
Danairat T.
Perl Modules for Database
161
• Install the Perl DBD for Postgres Database:-
1. Download DBD module “DBD-Pg-2.15.1.tar.gz” from
www.cpan.org
2. Unzip as a directory and cd to the directory
gzip -cd DBD-Pg-2.15.1.tar.gz | tar xf -
3. Run standard perl module installationi. perl Makefile.PL
ii. make
iii. make test
iv. make install
4. Finished.
Danairat T.
Prepare Database Environment (Postgres)
162
1. Verify the system has the Postgres using pkginfo
• bash-3.00# pkginfo -i SUNWpostgr-server
• system SUNWpostgr-server The programs needed to create and run a PostgreSQL 8.1.1 7 server
• bash-3.00# pkginfo -i SUNWpostgr
• system SUNWpostgr PostgreSQL 8.1.17 client programs and libraries
• bash-3.00# pkginfo -i SUNWpostgr-libs
• system SUNWpostgr-libs The shared libraries required for any PostgreSQL 8.1.17 clients
• bash-3.00# pkginfo -i SUNWpostgr-server-data
• system SUNWpostgr-server-data The data directories needed to create and run a PostgreSQ L 8.1.8
server
• bash-3.00# pkginfo -i SUNWpostgr-contrib
• system SUNWpostgr-contrib Contributed source and binaries distributed with PostgreSQL 8.1.17
• bash-3.00# pkginfo -i SUNWpostgr-devel
• system SUNWpostgr-devel PostgreSQL 8.1.17 development header files and libraries
• bash-3.00# pkginfo -i SUNWpostgr-docs
• system SUNWpostgr-docs Extra documentation for PostgreSQL 8.1.8
Danairat T.
Prepare Database Environment (Postgres)
163
2. Create OS user for Postgres and Initialize the database:-
• #useradd -c 'PostgreSQL user' -d /export/home/postgres -m -s /bin/bash postgres
• #chown -R postgres:postgres /var/lib/pgsql
• #su - postgres
• bash-3.00$ initdb -D /var/lib/pgsql/data/mydata
• The files belonging to this database system will be owned by user "postgres".
• This user must also own the server process.
• The database cluster will be initialized with locale C.
• creating directory /var/lib/pgsql/data/mydata ... ok
• creating directory /var/lib/pgsql/data/mydata/global ... ok
• creating directory /var/lib/pgsql/data/mydata/pg_xlog ... ok
• creating directory /var/lib/pgsql/data/mydata/pg_xlog/archive_status ... ok
• creating directory /var/lib/pgsql/data/mydata/pg_clog ... ok
• creating directory /var/lib/pgsql/data/mydata/pg_subtrans ... ok
Danairat T.
Prepare Database Environment (Postgres)
164
• Create OS user for Postgres and Initialize the database (continue):-
• creating directory /var/lib/pgsql/data/mydata/pg_twophase ... ok
• creating directory /var/lib/pgsql/data/mydata/pg_multixact/members ... ok
• creating directory /var/lib/pgsql/data/mydata/pg_multixact/offsets ... ok
• creating directory /var/lib/pgsql/data/mydata/base ... ok
• creating directory /var/lib/pgsql/data/mydata/base/1 ... ok
• creating directory /var/lib/pgsql/data/mydata/pg_tblspc ... ok
• selecting default max_connections ... 100
• selecting default shared_buffers ... 1000
• creating configuration files ... ok
• creating template1 database in /var/lib/pgsql/data/mydata/base/1 ... ok
• initializing pg_authid ... ok
• enabling unlimited row size for system tables ... ok
• initializing dependencies ... ok
• creating system views ... ok
• loading pg_description ... ok
• creating conversions ... ok
• setting privileges on built-in objects ... ok
Danairat T.
Prepare Database Environment (Postgres)
165
• Create OS user for Postgres and Initialize the database (continue):-
• creating information schema ... ok
• vacuuming database template1 ... ok
• copying template1 to template0 ... ok
• copying template1 to postgres ... ok
• WARNING: enabling "trust" authentication for local connections
• You can change this by editing pg_hba.conf or using the -A option the
• next time you run initdb.
• Success. You can now start the database server using:
• postmaster -D /var/lib/pgsql/data/mydata
• or
• pg_ctl -D /var/lib/pgsql/data/mydata -l logfile start
Danairat T.
Prepare Database Environment (Postgres)
166
3. Start the Postgres database using:-
bash-3.00$ pg_ctl -D /var/lib/pgsql/data/mydata -l /tmp/postgres.log start
postmaster starting
bash-3.00$
4. See the Postgres Process ID
bash-3.00$ ps -ef |grep postgres
postgres 1281 1 0 12:02:58 pts/4 0:00 /usr/bin/postmaster -D /var/lib/pgsql/data/mydata
postgres 1283 1281 0 12:02:59 pts/4 0:00 /usr/bin/postmaster -D /var/lib/pgsql/data/mydata
postgres 1263 1134 0 11:59:13 pts/4 0:00 -bash
postgres 1327 1263 0 12:14:46 pts/4 0:00 ps -ef
postgres 1284 1281 0 12:02:59 pts/4 0:00 /usr/bin/postmaster -D /var/lib/pgsql/data/mydata
postgres 1285 1284 0 12:02:59 pts/4 0:00 /usr/bin/postmaster -D /var/lib/pgsql/data/mydata
Danairat T.
Prepare Database Environment (Postgres)
167
5. Access the database:-
-bash-3.00$ psql postgresWelcome to psql 8.1.17, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms\h for help with SQL commands\? for help with psql commands\g or terminate with semicolon to execute query\q to quit
postgres=#
Postgres Command Line UI Postgres Graphical UI
Danairat T.
Prepare Database Environment (Postgres)
168
6(a). Select the database:-
postgres=# select * from megaliths;
id | name | location | description | site_type_id | mapref
----+-------------+---------------+--------------------------+--------------+------------
1 | Stonehenge | Wiltshire | "Stone Circle and Henge" | 1 | SU 123 422
2 | Avebury | Wiltshire | "Stone Circle and Henge" | 2 | SU 103 700
3 | Sunhoney | Aberdeenshire | "Recumbent Stone Circle" | 2 | NJ 716 058
4 | Lundin | Links Fife | "Four Poster" | 3 | NO 404 027
5 | Callanish I | Western Isles | "Stone Circle and Rows" | 3 | NB 213 330
(5 rows)
Postgres Command Line UI
Danairat T.
Prepare Database Environment (Postgres)
169
6(b). Select the database:-
Postgres Graphical UI
Danairat T.
Prepare Database Environment (Postgres)
170
7. Shutdown the Postgres database:-
bash-3.00$ pg_ctl -D /var/lib/pgsql/data/mydata stop
waiting for postmaster to shut down.... done
postmaster stopped
Danairat T.
Database Handler
171
• Using the DBI to connect to Postgress and return to the DB handler
#!/usr/bin/perluse strict;use warnings;use DBI;
# db name is postgres, user is postgres and password is noneif (my $dbh = DBI->connect("dbi:Pg:dbname=postgres", "postgres", "")) {print "Connected.\n";} else {print "Could not connect to DB $DBI::errstr\n";}
exit(0);
DBHandlerEx01.pl
Results:-Connected.
Danairat T.
Database Statement
172
#!/usr/bin/perluse strict;use warnings;use DBI;
# Connect to the databaseif (my $dbh = DBI->connect("dbi:Pg:dbname=postgres", "postgres", "")) {# Statement from DB handlermy $sth = $dbh->prepare( "SELECT * FROM megaliths" )or die "Can't prepare SQL statement: $DBI::errstr\n";
# Execute the statement in the database$sth->execute()or die "Can't execute SQL statement: $DBI::errstr\n";$sth->finish()or die "Error finish the SQL statement: $DBI::errstr\n";# Disconnect database$dbh->disconnect()or warn "Error disconnecting: $DBI::errstr\n";
} else {print "Could not connect to DB $DBI::errstr\n";}
exit(0);
DBSthEx01.pl
Results:-
<no displayed result>
Danairat T.
Database Manipulation
173
• Retrieve database records
#!/usr/bin/perluse strict;use warnings;use DBI;# 1. Connect to the databaseif (my $dbh = DBI->connect("dbi:Pg:dbname=postgres", "postgres", "")) {my $sth = $dbh->prepare( "SELECT * FROM megaliths" )or die "Can't prepare SQL statement: $DBI::errstr\n";
# 2. Execute the statement in the database$sth->execute() or die "Can't execute SQL statement: $DBI::errstr\n";# 3. Retrieve DB recordsmy @row;while ( @row = $sth->fetchrow_array() ) {my ($id, $name, $location, $desc, $siteId, $mapRef) = @row;print "id=$id, name=$name, location=$location, mapRef=$mapRef\n";
}# 4. Finish the statement$sth->finish() or die "Error finish the SQL statement: $DBI::errstr\n";# 5. Disconnect database$dbh->disconnect()or warn "Error disconnecting: $DBI::errstr\n";
} else {print "Could not connect to DB $DBI::errstr\n";}exit(0);
DBSelectEx01.pl
Results:-
id=1, name=Stonehenge, location=Wiltshire, mapRef=SU 123 422
id=2, name=Avebury, location=Wiltshire, mapRef=SU 103 700
id=3, name=Sunhoney, location=Aberdeenshire, mapRef=NJ 716 058
id=4, name=Lundin, location=Links Fife, mapRef=NO 404 027
id=5, name=Callanish I, location=Western Isles, mapRef=NB 213 330
Danairat T.
Database Manipulation
174
• Add new records
#!/usr/bin/perluse strict;use warnings;use DBI;
my $newRecord = "6, Stone Big, The Area 51, The most biggest stone, 3, CA 8759 993";# Connect to the databaseif (my $dbh = DBI->connect("dbi:Pg:dbname=postgres", "postgres", "")) {# Prepare the statementmy $sth = $dbh->prepare( "INSERT INTO megaliths (id, name, location, description, site_type_id,mapref) VALUES (?,?,?,?,?,?)" )
or die "Can't prepare SQL statement: $DBI::errstr\n";
# Extract the input to variablemy ($id, $name, $location, $description, $site_type_id, $mapref) = split (/,/,$newRecord);
# Execute the statement in the database$sth->execute($id, $name, $location, $description, $site_type_id, $mapref)or die "Can't execute SQL statement: $DBI::errstr\n";
# Finish the statement$sth->finish() or die "Error finish the SQL statement: $DBI::errstr\n";
# Disconnect database$dbh->disconnect()or warn "Error disconnecting: $DBI::errstr\n";
} else {print "Could not connect to DB $DBI::errstr\n";}exit(0);
DBAddEx01.pl
Results:-
<please see the db result there is one new record inserted>
Danairat T.
Database Manipulation
175
• Update records from table
#!/usr/bin/perluse strict;use warnings;use DBI;
my $newRecord = "6, Stone Biggest, The Area 51, The most biggest stone, 3, CA 8759 993";# Connect to the databaseif (my $dbh = DBI->connect("dbi:Pg:dbname=postgres", "postgres", "")) {# Prepare the statementmy $sth = $dbh->prepare( "UPDATE megaliths SET name=? WHERE (id=?)" )or die "Can't prepare SQL statement: $DBI::errstr\n";
# Extract the input to variablemy ($id, $name, @others) = split (/,/,$newRecord);
# Execute the statement in the database$sth->execute($name, $id)or die "Can't execute SQL statement: $DBI::errstr\n";
# Finish the statement$sth->finish() or die "Error finish the SQL statement: $DBI::errstr\n";
# Disconnect database$dbh->disconnect()or warn "Error disconnecting: $DBI::errstr\n";
} else {print "Could not connect to DB $DBI::errstr\n";}exit(0);
DBUpdateEx01.pl
Results:-
<please see the db result >
Danairat T.
Database Manipulation
176
• Delete records from table
#!/usr/bin/perluse strict;use warnings;use DBI;
my $newRecord = "6, Stone Biggest, The Area 51, The most biggest stone, 3, CA 8759 993";# Connect to the databaseif (my $dbh = DBI->connect("dbi:Pg:dbname=postgres", "postgres", "")) {# Prepare the statementmy $sth = $dbh->prepare( "DELETE FROM megaliths WHERE (id=?)" )or die "Can't prepare SQL statement: $DBI::errstr\n";
# Extract the input to variablemy ($id, @others) = split (/,/,$newRecord);
# Execute the statement in the database$sth->execute($id)or die "Can't execute SQL statement: $DBI::errstr\n";
# Finish the statement$sth->finish() or die "Error finish the SQL statement: $DBI::errstr\n";
# Disconnect database$dbh->disconnect()or warn "Error disconnecting: $DBI::errstr\n";
} else {print "Could not connect to DB $DBI::errstr\n";}exit(0);
DBDeleteEx01.pl
Results:-
<please see the db result >
top related