Power Point File

advertisement
Oracle SQL Query and
Transactions
By
Shyam Gurram
•
<?php
// Attempt to connect with user schema and password, then TNS alias.
Connecting to Oracle Using
the OCI8 Libraries
• There are only four OCI8 library
functions that govern opening and
closing connections. There is also the
oci_error() function that returns error
messages when you fail to connect to the
database.
if ($c = @oci_connect("php","php","xe"))
{
echo "Successfully connected to Oracle.<br>";
oci_close($c);
}
else
{
$errorMessage = oci_error();
print '<table border="1" cellpadding="0" cellspacing="0">';
foreach ($errorMessage as $name => $value)
print '<tr><td>'.$name.'</td><td>'.$value.'</td></tr>';
print '</table>';
}
?>
Connecting to Oracle Using the OCI8 Libraries
• Standard connections : All calls to the database in these scripts use the
same connection unless they open a unique connection by calling the
oci_new_connect() function. Standard connections place overhead on the
server to marshal and allocate resources that are dismissed when released by
the script or after the script terminates. There is no preserved state between
HTTP requests to the server for standard connections.
Oracle Call Interface-OCI
•
•
•
•
•
•
•
•
•
OCIPLogon -- Connect to an Oracle database
OCILogOff -- Disconnects from Oracle
OCIParse -- Parse a query and return a statement
OCIExecute -- Execute a statement
OCIError -- Return the last error
OCIFetchInto -- Fetches the next row into varresult
OCIFetch -- Fetches the next row into result-buffer
OCIResult -- Returns column value for fetched row
OCICommitt – Save transaction data to database
Connecting to Oracle Using the OCI8 Libraries
• oci8.priviliged_connect: This option enables you to make privilege connections under both
SYSOPER and SYSDBA roles. By default these are disabled; you enable them by setting the
directive to 1.
• oci8.max_persistent: This option enables you set the maximum number of persistent
connections per process. By default there is no limit. You set a limit by using a positive integer
value or 0 to disable persistent connections.
• oci8.persistent_timeout : This option sets the maximum time, measured in seconds, that an idle
persistent connection will remain alive. The default sets persistent connections open indefinitely.
• oci8.ping_interval: This option governs the interval between active pings of persistent
connections. Disabling it does speed processing of persistent connections but simultaneously
stops detection of network communication checks, which can lead to errors later in script
execution. Setting it to 0 reduces the
Sample Code Using OCICommitt
•
<?php
// Login to Oracle server
$conn = OCILogon('scott', 'tiger');
// Parse SQL
$stmt = OCIParse($conn, "INSERT INTO employees (name, surname) VALUES ('Maxim', 'Maletsky')");
// Execute statement
OCIExecute($stmt);
// Commit transaction
$committed = OCICommit($conn);
// Test whether commit was successful. If error occurred, return error message
if (!$committed) {
$error = OCIError($conn);
echo 'Commit failed. Oracle reports: ' . $error['message'];
}
// Close connection
OCILogoff($conn);
?>
Connecting to Oracle Using the OCI8 Libraries
• oci_close() : The oci_close() function explicitly closes an open OCI8
connection while the script that opened the connection is running. It is the
new behavior of the OCI8 library beginning with PHP 5.1.2. It has one
mandatory parameter, which is a resource connection. It returns a Boolean
true value when successful and false otherwise. You do not need to explicitly
include the oci_close() function, because it is implicitly called when your
script ends execution. It has the following pattern:
bool oci_close(resource connection)
Connecting to Oracle Using the OCI8 Libraries
• The call to the oci_connect() function provides the username, password, and
tnsnames .ora file network alias. You need to edit this and subsequent scripts
if you are using a different username, password, or network alias. When the
program connects to the Oracle database successfully.
• The script uses the sleep() function to create processing delays between
connections.
OCIError eg.
$c = ocilogon("u","p");
if (! $c) var_dump(ocierror()); // we have no connection yet
// so the error is stored global.
from tubu");
if (! $s) var_dump(ocierror($c)); // parse failed - error is
// stored in connection handle
$err = ociexecute($s);
if ( !$err) var_dump(ocierror($s)); // error code for ociexecute()
// is stored in the statement handle
$s = ociparse($c,"select *
PHP / Oracle Example
<HTML> <HEAD>
<TITLE>Using PHP to Read a Table in Oracle </TITLE> </HEAD>
<BODY BGCOLOR="#FFFFFF">
<CENTER><B>Authors</B> <BR><BR>
<?php
$DB_USERNAME='jceddia';
$DB_PASSWORD='jpasswd';
$DB_DATABASE='cse2030';
$connection = ocilogon($DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);
$stmt = OCIParse($connection, "SELECT * FROM author");
$err = OCIExecute($stmt);
PHP / Oracle Example cont.
// Start of table and column headings (ID and Name)
print "<TABLE CELLSPACING=\"0\" CELLPADDING=\"3\" BORDER=\"1\">\n";
print " <TR><TH>AID</TH><TH>Firstname</TH><TH>Surname</TH></TR>\n";
// Loop through results
while(OCIFetch($stmt))
{
print " <TR>\n";
print " <TD>" . OCIResult($stmt, "AID") . "</TD>\n";
print " <TD>" . OCIResult($stmt, "FNAME") . "</TD>\n";
print " <TD>" . OCIResult($stmt, "SNAME") . "</TD>\n";
print " </TR>\n";
}
print "</TABLE>\n";
OCIFreeStatement($stmt);
OCILogoff($connection);
?>
Fetch Types
• $stmt->fetch(PDO_FETCH_BOTH)
•
•
Array with numeric and string keys
default option
• PDO_FETCH_NUM
•
Array with numeric keys
• PDO_FETCH_ASSOC
•
Array with string keys
• PDO_FETCH_OBJ
•
$obj->name holds the ‘name’ column from the row
• PDO_FETCH_BOUND
•
Just returns true until there are no more rows
Connecting to Oracle Using the OCI8 Libraries
• There are three approaches to writing subroutines that are known as functions,
methods, and procedures. They are
• A classic pass-by-value function uses formal parameters as input-only variables,
which hold copies of values passed as actual parameters. The formal parameters are
defined as variables with local scope and the function returns only one value, which
can be a scalar or compound variable. The latter compound variable type is often
passed as a memory reference or pointer. This is the defined behavior of PL/SQL
functions and one of two function styles supported in PHP.A classic pass-byreference function uses formal parameters as input
Connecting to Oracle Using the OCI8 Libraries
• A classic pass-by-reference function uses formal parameters as input or input and
output variables. Input-only variables hold copies of values passed as actual
parameters, while input and output variables hold a memory reference to a variable.
The input-only formal parameters are defined as variables with local scope, and the
input and output formal parameters are defined as local variables with external
scope set by the calling program unit. These functions can return both (a) one value
that can be a scalar or compound variable, and (b) the altered contents of any input
and output actual parameters. While a classic pass-by-reference function is
acceptable in PHP, it is disallowed in PL/SQL functions.
• A classic procedure is a restricted pass-by-reference function that has a void return
Using the OCI8 Function Library
• The OCI8 function library contains a library function to connect to, transact
against, and disconnect from the Oracle database server. It also includes
libraries for working with collections and Large Objects (LOBs). The
preceding section demonstrated the utility of the three connection functions
and one disconnection function
Using the OCI8 Function Library
• oci_cancel() : The oci_cancel() function terminates a cursor and frees all available resources previously allocated to the
cursor. The function returns a Boolean true when successful and otherwise false. It has one mandatory parameter, which is
a resource statement. The oci_cancel() function has the following pattern: bool oci_cancel(resource statement).
• oci_commit() : This function issues a transaction control language COMMIT command to the current session, which
makes any changes to the data permanent. The function returns a Boolean true when successful and otherwise false. It has
one mandatory parameter, which is a resource statement. The oci_commit() function has the following pattern:
bool oci_commit(resource connection)
• oci_define_by_name() :
The oci_define_by_name() function defines a PHP variable and maps it to a column name
returned by a query statement. You call oci_define_by_name() before you execute the oci_execute() function, or there is no
assignment to the local PHP variable. The function returns a Boolean true when successful and otherwise false. It has four
parameters; three are mandatory, and one is optional. The first and second parameters are passed by value; one is a
statement resource, and the second is a string name in uppercase that maps to an Oracle column name variable. The third is
the new PHP variable that will contain the result from the query. The fourth is a data type, which uses the
Using the OCI8 Function Library
• oci_field_size() :The oci_field_size() function returns the size of Oracle variable-length strings, like the
VARCHAR2 data type. It returns the size in bytes of the field. The function has two mandatory parameters;
one is a statement resource. The other is an int representing the position of the field or the field name in the
fetched row. Fields are numbered 1 to 999 in the Oracle Database 10g family of products. The function has
the following pattern:
int oci_field_size( resource statement ,mixed field_name_or_position)
• oci_field_type() : function returns the data type of a fetched field. It returns the data type for the data field,
which enables the data value to be treated as a number or date as opposed to a string. You can find the list of
possible values in Table H-2. The function has two mandatory parameters; one is a statement resource, and
the other is an int representing the position of the field in the fetched row. Fields are numbered 1 to 999 in
the Oracle Database 10g family of products. The function has the following pattern:
mixed oci_field_type( resource statement ,mixed field_position)
Using the OCI8 Function Library
• oci_password_change() The oci_password_change() function lets you change a user
password. There are two ways to use this function. One use returns a Boolean value, and the
other, a resource connection. When returning a Boolean value, it returns a true on success
and false when encountering an error. The function has four mandatory parameters. The
first is a resource connection or a network alias defined in your tnsnames.ora file. When the
first parameter is a connection, the function returns a Boolean value. The function returns a
resource when the first parameter is a connection resource. The second parameter is a
username, the third, a current password, and the fourth, a new password. The function has
the following patterns:
bool oci_password_change( resource connection ,string user_name ,string old_password
,string )
Using the OCI8 Function Library
• oci_server_version() :The oci_server_version() function returns the database server product
version information. It returns a string containing the version number or a Boolean false
otherwise. The function has one mandatory parameter, which is a resource connection. The
function has the following pattern:
string oci_server_version( resource connection)oci_set_prefetch() ocisetprefetch()
• The oci_set_prefetch(): function resets the prefetch number of rows returned from an executed
query, overriding the oci8.default_prefetch directive in the php.ini file. The function returns a
Boolean true when successful and otherwise false. The function has two parameters, one
mandatory and the other optional. The first, mandatory, parameter is a resource connection, and
the second, optional, parameter is the number of rows to prefetch when executing the query. The
default for fetched rows is 1. The function has the following pattern:
bool oci_set_prefetch( resource connection [,int fetched_rows])
Querying and Transacting Using SQL
Statements
• The use of static SQL statements has practical limitations. It is impossible to
know what your end users will select, insert, update, and delete in your web
applications.
• Oracle bind variables act like substitution variables. They are Oracle
structures that let you pass scalar variables into and out of SQL statements
and PL/SQL statements in your PHP programs. Bind variables also let you
move data across memory spaces. In PHP programs bind variables let you
seamlessly pass a PHP variable to Oracle and vice versa.
Download