现在的位置: 首页 > 综合 > 正文

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

2013年09月09日 ⁄ 综合 ⁄ 共 11912字 ⁄ 字号 评论关闭

 

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=

抱歉!评论已关闭.