[SQL Relay文档] SQL Relay用于PHP Pear DB API的程序设计 (英文)

2552人阅读 评论(0) 收藏 举报

 

Programming with SQL Relay using the PHP Pear DB API

Establishing a Session

To use SQL Relay, you have to identify the connection that you intend to use.

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

... execute some queries ...

$db->disconnect();

?>

In this connect string, the following components have the following meanings:

testuser - the username to use to connect to the SQL Relay server, corresponds to the username in an entry in the "users" tag of the sqlrelay.conf file
testpassword - the password to use to connect to the SQL Relay server, corresponds to the password in an entry in the "users" tag of the sqlrelay.conf file
testhost - the hostname that the SQL Relay server is running on
9000 - the port that the SQL Relay server is listening on
testdb - this parameter is ignored; the pear DB spec requires that a database name be included in the connect string, but the database that SQL Relay is connected to is defined in the sqlrelay.conf file

After calling the constructor, a session is established when the first execute() is run.

For the duration of the session, the client stays connected to a database connection daemon. While one client is connected, no other client can connect. Care should be taken to minimize the length of a session.

If you're using a transactional database, ending a session has a catch. Database connection daemons can be configured to send either a commit or rollback at the end of a session if DML queries were executed during the session with no commit or rollback. Program accordingly.

Executing Queries

Call query() to run a query. query() will return DB_OK for successful DML or DDL queries or a result set for select queries.

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

if ($db->query("create table testtable (testnumber number, testchar char(40), testvarchar varchar2(40), testdate date, testlong long)")==DB_OK) {
        die ($db->getMessage());
}

if ($db->query("insert into testtable values (1,'testchar1','testvarchar1','01-JAN-2001','testlong1')")!=DB_OK) {
        die ($db->getMessage());
}

$res=$db->query("select * from testtable");

... process the result set ...

$res->free();

$db->disconnect();

?>

Commits and Rollbacks

If you need to execute a commit or rollback, you should use the commit() and rollback() functions rather than sending a "commit" or "rollback" query. There are two reasons for this. First, it's much more efficient to call the functions. Second, if you're writing code that can run on transactional or non-transactional databases, some non-transactional databases will throw errors if they receive a "commit" or "rollback" query, but by calling the commit() and rollback() functions you instruct the database connection daemon to call the commit and rollback API functions for that database rather than issuing them as queries. If the API's have no commit or rollback functions, the calls do nothing and the database throws no error. This is especially important when using SQL Relay with ODBC.

You can also turn Autocommit on or off by passing true or false to the autoCommit() function.

The following command turns Autocommit on.

$db->autoCommit(true);

The following command turns Autocommit off.

$db->autoCommit(false);

When Autocommit is on, the database performs a commit after each successful DML or DDL query. When Autocommit is off, the database commits when the client instructs it to, or (by default) when a client disconnects. For databases that don't support Autocommit, autoCommit() has no effect.

Temporary Tables

Some databases support temporary tables. That is, tables which are automatically dropped or truncated when an application closes it's connection to the database or when a transaction is committed or rolled back.

For databases which drop or truncate tables when a transaction is committed or rolled back, temporary tables work naturally.

However, for databases which drop or truncate tables when an application closes it's connection to the database, there is an issue. Since SQL Relay maintains persistent database connections, when an application disconnects from SQL Relay, the connection between SQL Relay and the database remains, so the database does not know to drop or truncate the table. To remedy this situation, SQL Relay parses each query to see if it created a temporary table, keeps a list of temporary tables and drops (or truncates them) when the application disconnects from SQL Relay. Since each database has slightly different syntax for creating a temporary table, SQL Relay parses each query according to the rules for that database.

In effect, temporary tables should work when an application connects to SQL Relay in the same manner that they would work if the application connected directly to the database.

Catching Errors

For most functions, you can find out if an error occurred by calling DB::isError() on the result.

When running DML or DDL queries, the query() function should return DB_OK. If it returns anything else, then that also indicates that an error has occurred. When running a select, query() returns a result set and DB::isError() must be used to determine if an error has occurred.

After determining that an error has occurred you can find out why by calling getMessage().

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

if ($db->query("create table testtable (testnumber number, testchar char(40), testvarchar varchar2(40), testdate date, testlong long)")!=DB_OK) {
        die ($db->getMessage());
}

if ($db->query("insert into testtable values (1,'testchar1','testvarchar1','01-JAN-2001','testlong1')")!=DB_OK) {
        die ($db->getMessage());
}

$res=$db->query("select * from testtable");
if (DB::isError($res)) {
        die ($db->getMessage());
}

... process the result set ...

$res->free();

$db->disconnect();

?>

Bind Variables

Programs rarely execute fixed queries. More often than not, some part of the query is dynamically generated. The Pear DB API provides means for using bind variables in those queries.

For a detailed discussion of substitutions and binds, see this document.

Here is an example where an associative array is used to bind a set of values to a set of variables. The values in the array are the values that will be substituted in place of the bind variables. The keys in the array may refer to either the name or (1-based) position of the bind variable. The query must be run by calling prepare() and execute(). The array is passed as the second parameter of the call to execute().

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$sth=$db->prepare("insert into testtable values (:var1,:var2,:var3,:var4,:var5)");
$bindvars=array("1" => 2,
                "2" => "testchar2",
                "3" => "testvarchar2",
                "4" => "01-JAN-2002",
                "5" => "testlong2");
$res=$db->execute($sth,$bindvars);

$db->disconnect();

?>

When passing a floating point number in as a bind or substitution variable, you have to supply precision and scale for the number. See this page for a discussion of precision and scale.

Re-Binding and Re-Execution

Another feature of the prepare/bind/execute paradigm is the ability to prepare, bind and execute a query once, then re-bind and re-execute the query over and over without re-preparing it. If your backend database natively supports this paradigm, you can reap a substantial performance improvement.

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$sth=$db->prepare("insert into testtable values (:var1,:var2,:var3,:var4,:var5)");

$bindvars=array("1" => 2,
                "2" => "testchar2",
                "3" => "testvarchar2",
                "4" => "01-JAN-2002",
                "5" => "testlong2");
$db->execute($sth,$bindvars);

$bindvars=array("var1" => 3,
                "var2" => "testchar3",
                "var3" => "testvarchar3",
                "var4" => "01-JAN-2003",
                "var5" => "testlong3");
$db->execute($sth,$bindvars);

$bindvars=array("1" => 4,
                "2" => "testchar4",
                "3" => "testvarchar4",
                "4" => "01-JAN-2004",
                "5" => "testlong4");
$db->execute($sth,$bindvars);

$bindvars=array("var1" => 5,
                "var2" => "testchar5",
                "var3" => "testvarchar5",
                "var4" => "01-JAN-2005",
                "var5" => "testlong5");
$db->execute($sth,$bindvars);


$db->disconnect();

?>

Accessing Fields in the Result Set

The fetchRow() and fetchInto() methods are useful for processing result sets. fetchRow() returns a row and fetchInto() populates a pre-allocated row. Both can be used to return ordered or associative arrays. The parameter to determine whether the array is ordered or associative may be passed directly into the call or (when using fetchRow()) may be set previously using setFetchMode().

Here is an example using fetchRow() to return an ordered array.

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$res=$db->query("select * from testtable");

# fetch the next row using ordered mode
$res->setFetchMode(DB_FETCHMODE_ORDERED);
$row=$res->fetchRow();
$field0=$row[0];
$field1=$row[1];
$field2=$row[2];
$field3=$row[3];
$field4=$row[4];

... do something with the fields ...

# fetch the next row passing ordered mode into fetchRow()
$row=$res->fetchRow(DB_FETCHMODE_ORDERED);
$field0=$row[0];
$field1=$row[1];
$field2=$row[2];
$field3=$row[3];
$field4=$row[4];

... do something with the fields ...

# fetch row 7 using ordered mode
$row=$res->fetchRow(DB_FETCHMODE_ORDERED,7);
$field0=$row[0];
$field1=$row[1];
$field2=$row[2];
$field3=$row[3];
$field4=$row[4];

... do something with the fields ...

$res->free();

$db->disconnect();

?>

Here is an example using fetchRow() to return an associative array.

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$res=$db->query("select * from testtable");

# fetch the next row using ordered mode
$res->setFetchMode(DB_FETCHMODE_ASSOC);
$row=$res->fetchRow();
$field0=$row['TESTNUMBER'];
$field1=$row['TESTCHAR'];
$field2=$row['TESTVARCHAR'];
$field3=$row['TESTDATE'];
$field4=$row['TESTLONG'];

... do something with the fields ...

# fetch the next row passing ordered mode into fetchRow()
$row=$res->fetchRow(DB_FETCHMODE_ASSOC);
$field0=$row['TESTNUMBER'];
$field1=$row['TESTCHAR'];
$field2=$row['TESTVARCHAR'];
$field3=$row['TESTDATE'];
$field4=$row['TESTLONG'];

... do something with the fields ...

# fetch row 7 using ordered mode
$row=$res->fetchRow(DB_FETCHMODE_ASSOC,7);
$field0=$row['TESTNUMBER'];
$field1=$row['TESTCHAR'];
$field2=$row['TESTVARCHAR'];
$field3=$row['TESTDATE'];
$field4=$row['TESTLONG'];

... do something with the fields ...

$res->free();

$db->disconnect();

?>

Here is an example using fetchInto() to populate an ordered array.

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$res=$db->query("select * from testtable");

# fetch the next row passing ordered mode into fetchInto()
$res->fetchInto($row,DB_FETCHMODE_ASSOC);
$field0=$row[0];
$field1=$row[1];
$field2=$row[2];
$field3=$row[3];
$field4=$row[4];

... do something with the fields ...

# fetch row 7 using ordered mode
$res->fetchInto($row,DB_FETCHMODE_ASSOC,7);
$field0=$row[0];
$field1=$row[1];
$field2=$row[2];
$field3=$row[3];
$field4=$row[4];

... do something with the fields ...

$res->free();

$db->disconnect();

?>

Here is an example using fetchInto() to populate an associative array.

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$res=$db->query("select * from testtable");

# fetch the next row passing ordered mode into fetchInto()
$res->fetchInto($row,DB_FETCHMODE_ASSOC);
$field0=$row['TESTNUMBER'];
$field1=$row['TESTCHAR'];
$field2=$row['TESTVARCHAR'];
$field3=$row['TESTDATE'];
$field4=$row['TESTLONG'];

... do something with the fields ...

# fetch row 7 using ordered mode
$res->fetchInto($row,DB_FETCHMODE_ASSOC,7);
$field0=$row['TESTNUMBER'];
$field1=$row['TESTCHAR'];
$field2=$row['TESTVARCHAR'];
$field3=$row['TESTDATE'];
$field4=$row['TESTLONG'];

... do something with the fields ...

$res->free();

$db->disconnect();

?>

The Pear DB API also provides convenience functions for fetching an entire result set, single row, single column or single value from a query, all in one step. setFetchMode() applies to some of these functions as well.

getAll() runs a query and fetches the entire result set, all in one step.

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

# get an ordered array using getAll
$db->setFetchMode(DB_FETCHMODE_ORDERED);
$rows=$db->getAll("select * from testtable");

echo("row 0:/n");
echo($row[0][0] . " " . $row[0][1] . " ");
echo($row[0][2] . " " . $row[0][3] . "/n");
... etc ...
echo("row 1:/n");
echo($row[1][0] . " " . $row[1][1] . " ");
echo($row[1][2] . " " . $row[1][3] . "/n");
... etc ...


# get an associative array using getAll
$db->setFetchMode(DB_FETCHMODE_ASSOC);
$rows=$db->getAll("select * from testtable");

echo("row 0:/n");
echo($row[0]['TESTNUMBER'] . " " . $row[0]['TESTCHAR'] . " ");
echo($row[0]['TESTVARCHAR'] . " " . $row[0]['TESTDATE'] . "/n");
... etc ...
echo("row 1:/n");
echo($row[1]['TESTNUMBER'] . " " . $row[1]['TESTCHAR'] . " ");
echo($row[1]['TESTVARCHAR'] . " " . $row[1]['TESTDATE'] . "/n");
... etc ...

$res->free();

$db->disconnect();

?>

getRow() runs a query and fetches the first row of the result set, all in one step.

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

# get an ordered array using getRow
$db->setFetchMode(DB_FETCHMODE_ORDERED);
$row=$db->getRow("select * from testtable");

echo($row[0] . " " . $row[1] . " ");
echo($row[2] . " " . $row[3] . "/n");


# get an associative array using getRow
$db->setFetchMode(DB_FETCHMODE_ASSOC);
$row=$db->getRow("select * from testtable");

echo($row['TESTNUMBER'] . " " . $row['TESTCHAR'] . " ");
echo($row['TESTVARCHAR'] . " " . $row['TESTDATE'] . "/n");

$res->free();

$db->disconnect();

?>

getCol() runs a query and fetches one entire column of the result set, all in one step.

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$col=$db->getCol("select * from testtable");

echo($col[0] . " " . $col[1] . " " . $col[2] . " " . $col[3] . "/n");

$res->free();

$db->disconnect();

?>

getOne() runs a query and fetches the first column of the first row, all in one step.

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$field=$db->getOne("select count(*) from testtable");

echo($field);

$res->free();

$db->disconnect();

?>

Cursors

Cursors make it possible to execute queries while processing the result set of another query. You can select rows from a table in one query, then iterate through it's result set, inserting rows into another table, using only 1 database connection for both operations.

For example:

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$res=$query("select * from my_first_table");

for (var $count=0; $count<$res->numRows(); $count=$count+1) {
        $row=$res->fetchRow();
        var $bindvars=array("1" => $row[0],
                                "2" => $row[1],
                                "3" => $row[2]);
        $sth=$db->prepare("insert into my_second_table values (:var1,:var2,:var3)");
        execute($sth,bindvars);
        $sth->free();
}

$res->free();

$db->disconnect();

?>

Getting Column Information

After executing a query, the column count may be retrieved using numCols(). Column data, including column name, type and length are available in the associative array returned from tableInfo(). tableInfo() takes a parameter indicating what values to populate the array with. This parameter may be empty, DB_TABLEINFO_ORDER, DB_TABLEINFO_ORDERTABLE or both values or'ed together.

An example calling numCols():

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$res=$query("select * from testtable");

echo("column count: " . $res->numCols() . "/n");

$db->disconnect()

?>

An example calling tableInfo():

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$res=$query("select * from testtable");

$tableinfo=$res->tableInfo();
echo "column 1:/n");
echo("name: " . $tableinfo[0]['name'] . "/n");
echo("type: " . $tableinfo[0]['type'] . "/n");
echo("len:  " . $tableinfo[0]['len'] . "/n");
echo("/n");
echo "column 2:/n");
echo("name: " . $tableinfo[1]['name'] . "/n");
echo("type: " . $tableinfo[1]['type'] . "/n");
echo("len:  " . $tableinfo[1]['len'] . "/n");
echo("/n");
echo "column 3:/n");
echo("name: " . $tableinfo[2]['name'] . "/n");
echo("type: " . $tableinfo[2]['type'] . "/n");
echo("len:  " . $tableinfo[2]['len'] . "/n");
echo("/n");
echo "column 4:/n");
echo("name: " . $tableinfo[3]['name'] . "/n");
echo("type: " . $tableinfo[3]['type'] . "/n");
echo("len:  " . $tableinfo[3]['len'] . "/n");
echo("/n");
echo "column 5:/n");
echo("name: " . $tableinfo[4]['name'] . "/n");
echo("type: " . $tableinfo[4]['type'] . "/n");
echo("len:  " . $tableinfo[4]['len'] . "/n");
echo("/n")4

$res->free();

$db->disconnect();

?>

An example calling tableInfo(DB_TABLEINFO_ORDER):

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$res=$query("select * from testtable");

$tableinfo=$res->tableInfo(DB_TABLEINFO_ORDER);
echo("num_fields: " . $tableinfo['num_fields'] . "/n");
echo("testnumber is field # " . $tableinfo['order']['TESTNUMBER'] . "/n");
echo("testchar is field # " . $tableinfo['order']['TESTCHAR'] . "/n");
echo("testvarchar is field # " . $tableinfo['order']['TESTVARCHAR'] . "/n");
echo("testdate is field # " . $tableinfo['order']['TESTDATE'] . "/n");
echo("testlong is field # " . $tableinfo['order']['TESTLONG'] . "/n");


$res->free();

$db->disconnect();

?>

An example calling tableInfo(DB_TABLEINFO_ORDERTABLE):

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$res=$query("select * from testtable");

$tableinfo=$res->tableInfo(DB_TABLEINFO_ORDERTABLE);
echo("testnumber is column # " . $tableinfo['ordertable']['']['TESTNUMBER'] . "/n");
echo("testchar is column # " . $tableinfo['ordertable']['']['TESTCHAR'] . "/n");
echo("testvarchar is column # " . $tableinfo['ordertable']['']['TESTVARCHAR'] . "/n");
echo("testdate is column # " . $tableinfo['ordertable']['']['TESTDATE'] . "/n");
echo("testlong is column # " . $tableinfo['ordertable']['']['TESTLONG'] . "/n");

$res->free();

$db->disconnect();

?>

An example calling tableInfo(DB_TABLEINFO_ORDER|DB_TABLEINFO_ORDERTABLE):

<?php

require_once 'DB.php';

$db = DB::connect("sqlrelay://testuser:testpassword@testhost:9000/testdb");
if (DB::isError($db)) {
        die ($db->getMessage());
}

$res=$query("select * from testtable");

echo("num_fields: " . $tableinfo['num_fields'] . "/n");
echo("testnumber is field # " . $tableinfo['order']['TESTNUMBER'] . "/n");
echo("testchar is field # " . $tableinfo['order']['TESTCHAR'] . "/n");
echo("testvarchar is field # " . $tableinfo['order']['TESTVARCHAR'] . "/n");
echo("testdate is field # " . $tableinfo['order']['TESTDATE'] . "/n");
echo("testlong is field # " . $tableinfo['order']['TESTLONG'] . "/n");

echo("testnumber is column # " . $tableinfo['ordertable']['']['TESTNUMBER'] . "/n");
echo("testchar is column # " . $tableinfo['ordertable']['']['TESTCHAR'] . "/n");
echo("testvarchar is column # " . $tableinfo['ordertable']['']['TESTVARCHAR'] . "/n");
echo("testdate is column # " . $tableinfo['ordertable']['']['TESTDATE'] . "/n");
echo("testlong is column # " . $tableinfo['ordertable']['']['TESTLONG'] . "/n");

$res->free();

$db->disconnect();

?>

Stored Procedures

Many databases support stored procedures. Stored procedures are sets of queries and procedural code that are executed inside of the database itself. For example, a stored procedure may select rows from one table, iterate through the result set and, based on the values in each row, insert, update or delete rows in other tables. A client program could do this as well, but a stored procedure is generally more efficient because queries and result sets don't have to be sent back and forth between the client and database. Also, stored procedures are generally stored in the database in a compiled state, while queries may have to be re-parsed and re-compiled each time they are sent.

While many databases support stored procedures. The syntax for creating and executing stored procedures varies greatly between databases.

SQL Relay supports stored procedures for most databases, but there are some caveats. Stored procedures are not currently supported when using FreeTDS against Sybase or Microsoft SQL Server. Blob/Clob bind variables are only supported in Oracle 8i or higher. Sybase stored procedures must use varchar output parameters.

Stored procedures typically take input paramters from client programs through input bind variables and return values back to client programs either through bind variables or result sets. Stored procedures can be broken down into several categories, based on the values that they return. Some stored procedures don't return any values, some return a single value, some return multiple values and some return entire result sets.

No Values

Some stored procedures don't return any values. Below are examples, illustrating how to create, execute and drop this kind of stored procedure for each database that SQL Relay supports.

Oracle

To create the stored procedure, run a query like the following.

create procedure testproc(in1 in number, in2 in number, in3 in varchar2) is
begin
        insert into mytable values (in1,in2,in3);
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

$sth=$db->prepare("begin testproc(:in1,:in2,:in3); end;");
$bindvars=array("in1" => 1,
                "in2" => 1.1,
                "in3" => "hello"})
$res=$db->execute($sth,$bindvars);

To drop the stored procedure, run a query like the following.

drop procedure testproc

Sybase and Microsoft SQL Server

To create the stored procedure, run a query like the following.

create procedure testproc @in1 int, @in2 float, @in3 varchar(20) as
        insert into mytable values (@in1,@in2,@in3)

To execute the stored procedure from an SQL Relay program, use code like the following.

$sth=$db->prepare("exec testproc");
$bindvars=array("in1" => 1,
                "in2" => 1.1,
                "in3" => "hello"})
$res=$db->execute($sth,$bindvars);

To drop the stored procedure, run a query like the following.

drop procedure testproc

Interbase and Firebird

To create the stored procedure, run a query like the following.

create procedure testproc(in1 integer, in2 float, in3 varchar(20)) as
begin
        insert into mytable values (in1,in2,in3);
        suspend;
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

$sth=$db->prepare("exec procedure testproc ?,?,?");
$bindvars=array("1" => 1,
                "2" => 1.1,
                "3" => "hello"})
$res=$db->execute($sth,$bindvars);

To drop the stored procedure, run a query like the following.

drop procedure testproc

DB2

To create the stored procedure, run a query like the following.

create procedure testproc(in in1 int, in in2 double, in in3 varchar(20)) language sql
begin
        insert into mytable values (in1,in2,in3);
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

$sth=$db->prepare("call testproc(?,?,?)");
$bindvars=array("1" => 1,
                "2" => 1.1,
                "3" => "hello"})
$res=$db->execute($sth,$bindvars);

To drop the stored procedure, run a query like the following.

drop procedure testproc

Postgresql

To create the stored procedure, run a query like the following.

create function testproc(int,float,varchar(20)) returns void as '
begin
        insert into mytable values ($1,$2,$3);
        return;
end;' language plpgsql

To execute the stored procedure from an SQL Relay program, use code like the following.

$res=$db->prepare("select testproc(:in1,:in2,:in3)");
$bindvars=array("in1" => 1,
                "in2" => 1.1,
                "in3" => "hello"})
$res=$db->execute($res,$bindvars);

To drop the stored procedure, run a query like the following.

drop procedure testproc


Single Values

Some stored procedures return single values. Below are examples, illustrating how to create, execute and drop this kind of stored procedure for each database that SQL Relay supports.

Oracle

To create the stored procedure, run a query like the following.

create function testproc(in1 in number, in2 in number, in3 in varchar2) returns number is
begin
        return in1;
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

$res=$db->prepare("select testproc(:in1,:in2,:in3) from dual");
$bindvars=array("in1" => 1,
                "in2" => 1.1,
                "in3" => "hello"})
$res=$db->execute($res,$bindvars);
$result=$res->fetchRow()[0];

To drop the stored procedure, run a query like the following.

drop function testproc

Sybase and Microsoft SQL Server

In Sybase and Microsoft SQL Server, stored procedures return values through output parameters rather than as return values of the procedure itself. However, the SQL Relay PHP Pear DB driver does not currently support output parameters.

Interbase and Firebird

To create the stored procedure, run a query like the following.

create procedure testproc(in1 integer, in2 float, in3 varchar(20)) returns (out1 integer) as
begin
        out1=in1;
        suspend;
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

$res=$db->prepare("select * from testproc(:in1,:in2,:in3)");
$bindvars=array("1" => 1,
                "2" => 1.1,
                "3" => "hello"})
$res=$db->execute($res,$bindvars);
$result=$res->fetchRow()[0];

To drop the stored procedure, run a query like the following.

drop procedure testproc

DB2

In DB2, stored procedures return values through output parameters rather than as return values of the procedure itself. However, the SQL Relay PHP Pear DB driver does not currently support output parameters.

Postgresql

To create the stored procedure, run a query like the following.

create function testfunc(int,float,char(20)) returns int as '
declare
        in1 int;
        in2 float;
        in3 char(20);
begin
        in1:=$1;
        return;
end;
' language plpgsql

To execute the stored procedure from an SQL Relay program, use code like the following.

$res=$db->prepare("select * from testfunc(:in1,:in2,:in3)");
$bindvars=array("1" => 1,
                "2" => 1.1,
                "3" => "hello"})
$res=$db->execute($res,$bindvars);
$result=$res->fetchRow()[0];

To drop the stored procedure, run a query like the following.

drop function testfunc(int,float,char(20))


Multiple Values

Some stored procedures return multiple values. Below are examples, illustrating how to create, execute and drop this kind of stored procedure for each database that SQL Relay supports.

Oracle

In Oracle, stored procedures can return values through output parameters or as return values of the procedure itself. If a procedure needs to return multiple values, it can return one of them as the return value of the procedure itself, but the rest must be returned through output parameters. However, the SQL Relay PHP Pear DB driver does not currently support output parameters.

Sybase and Microsoft SQL Server

In Sybase and Microsoft SQL Server, stored procedures return values through output parameters rather than as return values of the procedure itself. However, the SQL Relay PHP Pear DB driver does not currently support output parameters.

Interbase and Firebird

To create the stored procedure, run a query like the following.

create procedure testproc(in1 integer, in2 float, in3 varchar(20)) returns (out1 integer, out2 float, out3 varchar(20)) as
begin
        out1=in1;
        out2=in2;
        out3=in3;
        suspend;
end;

To execute the stored procedure from an SQL Relay program, use code like the following.

$sth=$db->prepare("select * from testfunc(?,?,?)");
$bindvars=array("1" => 1,
                "2" => 1.1,
                "3" => "hello"})
$res=$db->execute($sth,$bindvars);
$out1=$res->fetchRow()[0];
$out2=$res->fetchRow()[1];
$out3=$res->fetchRow()[2];

To drop the stored procedure, run a query like the following.

drop procedure testproc

DB2

In DB2, stored procedures return values through output parameters rather than as return values of the procedure itself. However, the SQL Relay PHP Pear DB driver does not currently support output parameters.

Postgresql

To create the stored procedure, run a query like the following.

create function testfunc(int,float,char(20)) returns record as '
declare
        output record;
begin
        select $1,$2,$3 into output;
        return output;
end;
' language plpgsql

To execute the stored procedure from an SQL Relay program, use code like the following.

$sth=$db->prepare("select * from testfunc(:in1,:in2,:in3) as (col1 int, col2 float, col3 char(20))");
$bindvars=array("in1" => 1,
                "in2" => 1.1,
                "in3" => "hello"})
$sth=$db->execute($sth,$bindvars);
$out1=$res->fetchRow()[0];
$out2=$sth->fetchRow()[1];
$out3=$res->fetchRow()[2];

To drop the stored procedure, run a query like the following.

drop function testfunc(int,float,char(20))


Result Sets

Some stored procedures return entire result sets. Below are examples, illustrating how to create, execute and drop this kind of stored procedure for each database that SQL Relay supports.

Oracle

Stored procedures in Oracle can return open cursors as return values or output parameters. A client-side cursor can be bound to this open cursor and rows can be fetched from it. However, the SQL Relay PHP Pear DB driver does not currently support output parameters.

Sybase and Microsoft SQL Server

Stored procedures in Sybase and Microsoft SQL Server can return a result set if the last command in the procedure is a select query, however SQL Relay doesn't currently support stored procedures that return result sets.

Interbase and Firebird

Stored procedures in Interbase and Firebird can return a result set if a select query in the procedure selects values into the output parameters and then issues a suspend command, however SQL Relay doesn't currently support stored procedures that return result sets.

DB2

Stored procedures in DB2 can return a result set if the procedure is declared to return one, however SQL Relay doesn't currently support stored procedures that return result sets.

Postgresql

To create the stored procedure, run a query like the following.

create function testfunc() returns setof record as '
        declare output record;
begin
        for output in select * from mytable loop
                return next output;
        end loop;
        return;
end;
' language plpgsql

To execute the stored procedure from an SQL Relay program, use code like the following.

$sth=$db->prepare("select * from testfunc() as (col1 int, col2 float, col3 char(20))");
$bindvars=array("in1" => 1,
                "in2" => 1.1,
                "in3" => "hello"})
$res=$db->execute($sth,$bindvars);
$row1=$res->fetchRow();
$row2=$res->fetchRow();
$row3=$res->fetchRow();
...

To drop the stored procedure, run a query like the following.

drop function testfunc
//From: http://sqlrelay.sourceforge.net/sqlrelay/programming/phppeardb.html
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3918097次
    • 积分:42380
    • 等级:
    • 排名:第85名
    • 原创:331篇
    • 转载:511篇
    • 译文:5篇
    • 评论:1257条
    文章存档
    最新评论