Title Goes Here - Binus Repository

Download Report

Transcript Title Goes Here - Binus Repository

Matakuliah
Tahun
: T0413
: 2009
PHP and SQL/J
Pertemuan 12
What is PHP?
PHP is the most popular Web language in the world today:
70% of the UNIX-based, Apache Web platform market… 40% + of the overall market
PHP is an open source, platform independent scripting language that
is designed for web application development
Originally created by Rasmus Lerdorf in 1995
Set of Perl scripts for tracking accesses to his online resume
Original name was 'Personal Home Page Tools‘
PHP 3.0 was a completed rewrite in 1997
Number of PHP developers has been growing ever since
It is one of the most widely deployed web languages in the world
today .
PHP means (PHP Hypertext Preprocessor)
Bina Nusantara University
3
Why PHP is popular ?
Rapid, iterative development
cycles with a low learning curve
Easily integrated into
heterogeneous
environments/systems
Bina Nusantara University
Robust, high-performance &
scalable; stable & secure
Proven through
widespread deployment;
vibrant community
4
PHP - Key driver of LAMP Stack
•
LAMP – Technical
– Linux, Apache HTTP Server, MySQL, PHP/Perl/Python
– Open Source web technology stack
• Often available on ISPs for reasonable monthly fees
– Pure open source software components
LAMP – Business (Appealing on many levels)
1. Rapid iterative development
2. Low cost of software acquisition
3. Scalable and robust scalable LAMP solutions requires significant
investment
• PHP Concerns (CTOs)
– Lack of Professional level PHP developer skills
• Good software design skills are still important for large projects
– Considerable investment in .NET or J2EE already
– Many enterprises are not comfortable with MySQL
Bina Nusantara University
5
PHP extensions/drivers
• ibm_db2
– Written, maintained and supported by IBM
– Can only be used to access DB2 databases
– Provides a procedural API with extensive access to the db
metadata
– Can be compiled with PHP 4 or PHP 5.
• pdo_ibm
– pdo_ibm is a driver for the PHP Data Objects (PDO) extension
– Provides an Object Oriented database abstraction layer
– Support starts with PHP 5.1
– PDO can work with many database vendors
• ibm_db2 and pdo_ibm are based on the IBM DB2 CLI Layer
• PHP drivers are offered under open-source licenses
– http://www.php.net
Bina Nusantara University
6
Setting up the PHP environment manually (Windows)
1. Download the precompiled binary version of PHP code and PECL
from www.php.net
– Unzip the PHP zip file into <install directory>
– Unzip the PECL zip file into <install directory> \ext subdirectory
2. Copy or rename php.ini-recommended file to php.ini
3. Add the following lines to php.ini:
– To enable the ibm_db2 extension:
extension=php_ibm_db2.dll
– To enable the PDO extension and pdo_ibm driver:
extension=php_pdo.dll
extension=php_pdo_ibm.dll
Bina Nusantara University
7
Setting up the PHP environment manually (cont’d)
4. Add the following to the httpd.conf file (Apache HTTP Server
2.x) to enable PHP support:
LoadModule php5_module ‘<install
directory>/php5apache2.dll'
AddType application/x-httpd-php .php
PHPIniDir ‘<install directory>'
5. Restart the Apache HTTP Server for the changes to take effect.
Bina Nusantara University
8
Connecting to a database – ibm_db2 extension
• db2_connect()
– For non-persistent connection
– Close with db2_close() or when a PHP script ends
• db2_pconnect()
– Persistent connection to a DB2 database
– PHP keeps the connection open for subsequent PHP scripts
ignoring calls to db2_close()
– May be better for performance
• Both return FALSE if unsuccessful connection
– Use db2_conn_error() and db2_conn_errormsg() to retrieve
diagnostic information
• Both return not FALSE if the connection attempt succeeded
Bina Nusantara University
9
Connecting to a database - Example
1
2
3
<?php
$database = 'SAMPLE';
$user
= 'rfchong';
$password = 'passwd';
$conn = db2_connect($database, $user,
$password);
if ($conn)
{ echo “Successful connection!";
db2_close($conn);
} else
{ echo "Connection failed."; }
?>
Bina Nusantara University
10
Retrieving database metadata – ibm_db2 extension
Function
Description
db2_client_info()
Returns metadata about the DB2 client
configuration.
db2_column_privileges( Lists the columns and associated privileges
db2_columns()
Lists the columns and associated metadata
db2_foreign_keys()
Lists the foreign keys for a table.
db2_primary_keys()
Lists the primary keys for a table.
db2_procedure_column Lists the parameters for one or more stored
db2_procedures()
Lists the stored procedures registered in the
db2_server_info()
Returns metadata about the database
software and configuration.
db2_special_columns()
Lists the unique row identifiers for a table.
db2_statistics()
Lists the indexes and statistics for a table.
Bina Nusantara University
db2_table_privileges()
11
Lists tables and their associated privileges in
Database Metadata example
1
2
3
<?php
$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');
$server = db2_server_info( $conn );
if ($server) {
echo "DBMS_NAME: ";
echo "DBMS_VER: ";
echo "DB_CODEPAGE: ";
echo "DB_NAME: ";
echo "INST_NAME: ";
echo "SPECIAL_CHARS: ";
db2_close($conn);
}
?>
Bina Nusantara University
var_dump(
var_dump(
var_dump(
var_dump(
var_dump(
var_dump(
$server->DBMS_NAME );
$server->DBMS_VER );
$server->DB_CODEPAGE );
$server->DB_NAME );
$server->INST_NAME );
$server->SPECIAL_CHARS );
12
Executing statements – ibm_db2 extension
• db2_exec()
– For single statements, with no input parameters
– If it returns FALSE, the statement failed:
• Use db2_stmt_error() and db2_stmt_errormsg() for info
about error
– If it did NOT return FALSE, the statement was successful:
• If the SQL statement selected rows using a scrollable
cursor, or inserted, updated, or deleted rows, call
db2_num_rows() to return the number of rows affected.
• If the SQL statement returned a result set, you can fetch
rows.
Bina Nusantara University
13
db2_exec example
1
2
3
<?php
$create = 'CREATE TABLE test (id INTEGER, name CHAR(30))';
$result = db2_exec($conn, $create);
if ($result)
{ print "Successful table creation\n"; }
?>
Example with an XQuery statement:
<?php
$xquery = '$doc/customerinfo/phone';
$stmt = db2_exec($conn, "select xmlquery('$xquery'
PASSING INFO AS \"doc\") from customer");?>
…
?>
Bina Nusantara University
14
Preparing & executing statements – ibm_db2 extension
• Use db2_prepare() and db2_execute
–
–
–
–
Bina Nusantara University
Use with parameter markers as input
Better performance than db2_exec()
May need to bind parameters with db2_bind_param()
Can use db2_fetch_assoc to fetch rows from a result set.
15
db2_execute example
2
$sql = "SELECT lastname FROM emp WHERE bonus > ? AND bonus < ?";
$stmt = db2_prepare($conn, $sql);
if (!$stmt)
{ // Handle errors }
3
// Explicitly bind parameters
db2_bind_param($stmt, 1, $_POST['lower']);
db2_bind_param($stmt, 2, $_POST[‘upper']);
1
4
5
db2_execute($stmt, array($_POST['lower‘],$_POST[‘upper’]);
while ($row = db2_fetch_assoc($stmt)) {
print "{$row['LASTNAME']}\n";
}
Bina Nusantara University
16
What is SQLJ?
• SQLJ allows for embedding SQL statements into Java programs.
• All SQL statements are run statically
• SQLJ programming uses “contexts”.
– A “Connection context” is equivalent to the Connection object
in JDBC
– A default connection context is used when no connection
context is specified
– An “Execution context” is required to get the information
regarding the SQL statement before and after executing the
statement.
Bina Nusantara University
17
SQLJ syntax
• Different syntax to use:
– #sql [connection-context] { sql statement }
– #sql [connection-context, execution context] { sql statement }
– #sql { sql statement }
– #sql [execution context] { sql statement }
• With this syntax, a precompiler can identify the statements to
translate: Start with “#sql” and use curly brackets as delimiters.
• Host variables can be used and identified by a colon. Eg:
#sql { SELECT EMPNO FROM EMP WHERE WORKDEPT = :dept};
Bina Nusantara University
18
Connection context
1
2
3
4
5
6
Connection context example:
#sql context ctx; // This should be outside the class
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
ctx ctx1 = new ctx(“jdbc:db2:sample”,false);
#sql [ctx1] { DELETE FROM dept };
Connection context from Connection object example:
#sql context ctx; // This should be outside the class
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
Connection con=DriverManager.getConnection();
ctx ctx1 = new ctx(con);
#sql [ctx1] { DELETE FROM dept };
Bina Nusantara University
19
Default context
1
2
3
Connection with default context example:
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance
();
Connection con = DriverManager.getConnection();
DefaultContext ctx1 = new DefaultContext(con);
DefaultContext.setDefaultContext(ctx1);
#sql { DELETE FROM dept };
Bina Nusantara University
20
Execution context
• Within a connection context object, execute any SQL
statement.
• Use the ExecutionContext class to monitor and control the SQL
statements while executing. Equivalent to the JDBC
“statement” interface.
• Create an ExecutionContext objext with the
getExecutionContext method of the connection context.
• Some ExecutionContext methods work before an SQL
statement is executed while others apply only after execution.
Bina Nusantara University
21
Execution context
1
2
3
#sql context ctx; // this should be outside the class
String url = "jdbc:db2:sample";
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
Connection con=DriverManager.getConnection(url);
ctx ctx1=new ctx(con);
ExecutionContext exectx1 = ctx1.getExecutionContext();
#sql[ctx1,exectx1] = { DELETE FROM purchaseorder WHERE
status='UnShipped'}
int i = exectx1.getUpdateCount();
Bina Nusantara University
22
Iterators
• Iterators are equivalent to a JDBC result set
• Two types of iterators:
– Named iterators
• Identify a row by the name of the column in the result set.
• While defining the named iterator, specify the name of the
columns and their data types
– Position iterators
Bina Nusantara University
• Identify a row by its position in the result set.
• While defining the position iterator, specify only the data
types of the columns.
23
Named iterator example
1
2
3
4
5
6
#sql iterator namediterator (int poid, String status)
namediterator iterator1;
#sql [ctx1] iterator1 = { select poid,status from
purchaseorder };
while(iterator1.next()) {
System.out.println("poid: " + iterator1.poid() + "Status:
"+
iterator1.status());
}
iterator1.close();
Bina Nusantara University
24
Positioned iterator example
1
2
3
4
5
6
7
8
9
#sql iterator positionedIterator (int, String);
String status = null;
int poid = 0;
positionedIterator iterator1;
#sql [ctx1] iterator1={ select poid, status from
purchaseorder };
#sql { fetch :iterator1 into :poid, :status };
while(!iterator1.endFetch()) {
System.out.println("poid: " + poid + "Status: "+ status);
#sql { fetch :iterator1 into :poid, :status };
}
Bina Nusantara University
25
Updatable and scrollable iterators
• Iterators in SQLj are read-only and can only move
forward by default.
• To define a scrollable iterator, you need to implement
sqlj.runtime.Scrollable while defining the iterator.
• To define an updatable cursor, you need to
implement sqlj.runtime.ForUpdate while defining
the iterator.
– When defining an updatable iterator, you also need to
specify the columns you would like to update.
Bina Nusantara University
26
Updatable and scrollable iterators
1
2
3
4
5
6
7
8
#sql public iterator namediterator implements sqlj.runtime.ForUpdate
with (updateColumns="STATUS") (int poid, String status);
namediterator iterator1;
#sql [ctx1] iterator1={ select poid,status from purchaseorder };
while(iterator1.next()) {
System.out.println("before update poid: " + iterator1.poid() +
"Status: "+ iterator1.status());
if(iterator1.status().toUpperCase().compareTo("UNSHIPPED")==0)
#sql [ctx1] {update purchaseorder set status=
'shipped' where current of :iterator1 };
}
#sql [ctx1] {commit};
Bina Nusantara University
27
Preparing an SQLJ program
myapp_SJProfile0.ser
myapp_SJProfile1.ser
DB2
Customizer
db2sqljcustomize
Package
myapp.sqlj
SQLJ
Translator
java myapp
sqlj
myapp.java
Java
Compiler
myapp.class
javac
Bina Nusantara University
28
Translation using “sqlj”
•
“sqlj” is the SQLJ translator. The syntax is:
sqlj <options> filename
For example: sqlj myprg3.sqlj
•
“sqlj” in the above example will create several files:
– myprg3.java:
• The generated source program
– myprg3.class:
• The class file after sqlj invokes javac
– myprg3_SJProfile0.ser:
• A serialized profile file for each connection context class that is
used in an SQLJ executable clause
– myprg3_SJProfileKeys.class:
• The class file after sqlj invokes javac
Bina Nusantara University
29
Customization using “db2sqljcustomize”
• “db2sqljcustomize” is the DB2 Customizer. The syntax is:
db2sqljcustomize <options> filename
For example:
db2sqljcustomize -url jdbc:db2://localhost:50000/sample
-user rfchong -password mypasswd myprg3_SJProfile0.ser
In this example we are using these options:
• -url jdbc:db2://localhost:50000/sample
– Is the URL needed to connect to the database
• -user rfchong
– user ID to connect to the database
• -password mypasswd
– password to connect to the database
myprg3_SJProfile0.ser is the file name to “customize” to create the package
in the db
Bina Nusantara University
30