31
1 Database access with Java, ADODB and PDO Bruno Defude INF

Database access with Java, ADODB and PDO · PDF file2 CGI scripts and DBMS access browser http Server CGI Prog. DBMS HTTP/CGI request Q_S SQL API data Dynamic HTML page 1 2 3 4

Embed Size (px)

Citation preview

1

Database access with Java,

ADODB and PDO

Bruno Defude

INF

2

CGI scripts and DBMS access

browser http

ServerCGI Prog.

DBMS

HTTP/CGI requestQ_S

SQL

APIdata

Dynamic HTML page

1

23

4

3

Objective of a CGI/DBMS script

� Produce a completely dynamic HTML page usingdata extracted from the DB

� HTML page or form (more active)

� Three main functions:

� decode HTTP request parameters and translate them intoSQL queries

� Run SQL queries

� Encode results with HTML tags (completely written withexplicite PRINT)

4

PHP scripts and DBMS access

browser http

Server

PHP Prog.

DBMS

HTTP request

SQL

dynamic HTML page HTML page

+ PHP

PHP

Interpreter

Dynamic

HTML Page

1

2

3

45

6

7

5

Objective of an active page

• Produce a partly dynamic HTML page using data

extracted from the DB

– HTML page or form (more active)

• Three main functions:

– decode HTTP request parameters and translate them

into SQL queries (more simple compared to CGI)

– Run SQL queries

– Encode results with HTML tags (partly written with

explicite PRINT and partly written in the HTML page)

6

DBMS access programming

7

Java/JDBC Example

Java/JDBC Prog.

javac

Java Bytecode

javaOracle Driver

Java class (.zip)

8

Java-JDBC Program

import java.sql.*;

Class.forName("oracle.jdbc.driver.OracleDriver");

String dburl = "jdbc:oracle:thin:@mica:1521:IOBD";

Connection conn = DriverManager.getConnection(dburl, "MsCCCN", "msc");

java.sql.Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT number, sname FROM STUDENTS");

while (rs.next())

{

int i = rs.getInt("number");

String s = rs.getString("sname");

System.out.println("STUDENT = " + i + " " + s+ "<br>");

}

9

PHP-MySQL

PHP-MySQL Prog.

PHP InterpreterDBMS Lib +

PHP Lib

results

10

PHP MySQL Program

$db=mysql_connect("localhost", "user", "passwd");

mysql_select_db("MsCCCN", $db);

$result=mysql_query("select number, sname from STUDENTS", $db);

if ($result==false) die("failed");

while($student=mysql_fetch_object($result)) {

echo « STUDENT = $student->number $student->sname<br>\n" ;

}

11

PHP + DBMS abstract API

PHP-AdoDB Prog.

PHP Interpreter

DBMS Lib +

PHP Lib +

Adodb lib

results

12

PHP Adodb Program

include ("adodb.inc.php");

$db=&ADONewConnection(‘mysql’);

$db->connect("localhost", "user", "passwd" , "MsCCCN");

$students=$db->Execute("select number, sname from STUDENTS");

if ($students==false) die("failed");

while($student=$students->FetchRow()) {

print « STUDENT = $student[0] $student[1] <br>\n" ;

}

13

PHP5 + PDO (PHP Data Objects)

Prog. PHP5-PDO

PHP5 InterpreterLib SGBD+

Lib PHP5

results

14

PHP5 PDO Program

try {$dbh = new PDO("mysql:host=localhost;dbname=mydb", "user",

"passwd");echo 'Connected to database';

$sql = "SELECT NUM, CRU FROM vins";foreach ($dbh->query($sql) as $row)

{print $row[‘NUM'] .' - '. $row[‘CRU'] . '<br />';}

/*** close the database connection ***/$dbh = null; }

catch(PDOException $e){echo $e->getMessage();}

15

PHP and DBMS

� Native API for each DBMS or abstract levelwith drivers (no standard with PHP <5: AdoDB, phplib, Peer db, … in PHP5 PDO)

� Interpreted approach for SQL queries (no static verification at compile-time of SQL queries)

16

Main Functions

PHP-MySQL� int mysql_affected_rows(int connection): give the number of

tuples, deleted, inserted ou updated by last SQL statement

� int mysql_close (int connection): close MySQL connection(implicite at the end of the script)

� int mysql_connect(string chaine_connection, string name, string passwd): open a new connection (returns negative number if problems)

� int mysql_db_query(string dbase, string query, int connection): process a SQL query to the database dbase in a connectioncontext. Returns a result id

17

PHP-MySQL Functions (2)

� int mysql_errno(int connection): returns the error number of the last SQL statement

� string mysql_erro(int connection): returns the error message (string) of the last SQL statement

� array mysql_fetch_array(int result): returns an associative arraycontaining attributes of the current tuple and go to the next tuple. This function returns false at the end of the result

� object mysql_fetch_object(int result): returns an object with eachproperty corresponding to an attribute of the current tuple and go on next tuple. This function returns false at the end of the result

18

PHP-MySQL Functions (3)

� array mysql_fetch_row (int result): returns an array

containing attributes of the current tuple and go on next tuple. This function returns false at the end of the result

� int mysql_query(string query, int connection) : process query in the connection context. Returns a result id if success, else false.

� int mysql_select_db(string dbase, int connection): select dbaseas current database. After this function call all queries will beprocessed on dbase.

19

Simple example

PHP-ADODB<?php

include(‘init-ado.php');

$connection = &ADONewConnection(‘mysql');

$connection->Connect (dbnode, dbuser, dbpasswd, dbinstance);

$connection->debug=true;

$rs=$connection->Execute('select num, sname fromsailors');

rs2html($rs);

?>

20

init-ado.php

<?php

include('/mci/inf/defude/adodb/adodb.inc.php');

include('/mci/inf/defude/adodb/tohtml.inc.php');

define("dbnode", "calcite");

define("dbuser", "user1");

define("dbpasswd", "user1");

define("dbinstance", "essai");

?>

21

ADODB-PHP Functions

� $connection->Connect ('‘, 'msc', 'msc', 'TANNA'): connection to the user ‘msc’ identified by password ‘msc’ on the Oracle nodeTANNA

� $connection->Connect (‘calcite’, ‘user1', ‘user1', ‘essai'): connection to the user ‘user1’ identified by password ‘user1’ on the mySQL database ‘essai’ on node ‘calcite’

� $connection->debug=true: set the debug mode to true

� $rs=$connection->Execute('select num, sname from sailors'): execute a SQL query (without unbind variables) and put the result in a resultset

� $res=$connection->Execute("insert into sailors(sid, sname,

rating, age) values (".$sid. ", ‘" .$sname. "’, " .$rating. ", " .$age.

") "): construct a string representing an insert statement and execute it

22

ADODB-PHP functions (2)

� $connection->ErrorMsg(): returns the errormessage associated to the last SQL statement

� $rs->FieldCount(): returns the number of attributein the resultset

� $rs->RecordCount(): returns the number of tuples accessed by the last SQL statement

� $ff = $rs->FetchField($i): returns an object (withthree fields) describing the field number $i of the resultset

� $ff->name (name of the attribute), $ff->type (type of the attribute), $ff->max-length (max size of the attribute)

23

ADODB-PHP functions (3)

� $arr = $rs->FetchRow(): access to the currenttuple, put it in the $arr array (access from 0 to n) and go on next tuple

� $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC: update the FECTH_MODE to ASSOC (mandatory to extract attributevalue using the name of attribute)

� $rs->Fields('SID'): returns the value of attribute ‘SID’ in the current tuple

24

PHP-AdoDB samples

� See PHP-Oracle samples

� See PHP-MySQL samples

25

PHP5 PDO Functions PDO class� PDO::beginTransaction — start a transaction� PDO::commit — commit a transaction� PDO::__construct —� PDO::errorCode —� PDO::errorInfo —� PDO::exec — run a non SELECT statement and returns the affected

number of rows� PDO::getAttribute —PDO::getAvailableDrivers —� PDO::lastInsertId —� PDO::prepare — Prepare a statement and returns an objet� PDO::query — run a SELECT query, returns a PDOStatement object� PDO::quote —� PDO::rollBack — rollback a transaction� PDO::setAttribute —

26

Fonctions PHP5 PDO classe PDO� PDOStatement->bindColumn —� PDOStatement->bindParam —� PDOStatement->bindValue —� PDOStatement->closeCursor —� PDOStatement->columnCount —� PDOStatement->errorCode —� PDOStatement->errorInfo —� PDOStatement->execute — run a prepared statement� PDOStatement->fetch — get the new row� PDOStatement->fetchAll —� PDOStatement->fetchColumn —� PDOStatement->fetchObject — get the new row as an object� PDOStatement->getAttribute —� PDOStatement->getColumnMeta —� PDOStatement->nextRowset —� PDOStatement->rowCount — returns the number of affected rows of the last

PDOStatement::execute()� PDOStatement->setAttribute —� PDOStatement->setFetchMode —

27

PDO examples

� Examples

� source code

� documentation PDO

� http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html: a tutorial on PDO programming

28

Sessions Programming

� login.php script: open a session storing 3 variables

� Idf = numerical value

� firstname = string

� lastname = string

� traite.php Script

� Test existing session

� print firstname+lastname

� logout.php Script

� Ends current session

29

cookie Solution

� login.php Script Setcookie(idf, "1234", now()+600, "/", ".it-sudparis.eu", 0);Setcookie(firstname, "defude", now()+600, "/", ".it-sudparis.eu", 0);Setcookie(lastname, "bruno", now()+600, "/", ".it-sudparis.eu", 0);

� traite.php Script if (!isset($_COOKIE[‘idf’])) { print ‘error session not started’; }else {print $_COOKIE[‘firstname’].’-’. $_COOKIE[‘lastname’];

� logout.php Script Setcookie(idf, "", 0, "", "", 0);Setcookie(firstname, "", 0, "", "", 0);Setcookie(latsname, "",, " ", "", 0);

30

session Solution

� login.php Script session_start(); $_SESSION[‘idf’]=1234;$_SESSION[‘firstname’]=‘defude’;$_SESSION[‘lastname’]=‘bruno’;

� traite.php Script session_start(); if (!isset($_SESSION[‘idf’])) { print ‘error session not started’;}else {print $SESSION [‘firstname’].’-’. $_SESSION[‘lastname’];}

� logout.php Script session_destroy();

31

PHP-BD Conclusion

� several possible APIs:� native APIs : efficient but code to adapt (from one

DBMS to another)

� abstract Interfaces : less efficient, no code to adapt, no standard for PHP < 5, PDO since PHP5

� Many similarities between all approaches