Databases: Basics
[
Basics |
Object Persistence
] uses('rdbms.DriverManager');
The connection object returned is an instance of a driver-specific subclass of the
DBConnection class. In the above example, the connection
object would be instance of SybaseConnection. Querying
To query a database using SQL statements, you can either use the generic query()
method or one of the insert(), update(), delete() and
select() methods. query
The query() method returns a ResultSet object
on which one can iterate. Its next() method return hashes with keys
corresponding to the database fields and values to their values. $q= $conn->query('select person_id, realname, lastchange from person where person_id= 1');
select
The select() method returns all results into an array of hashes and
is particularily useful when it comes to small resultsets. $a= $conn->select('author_id, person_id from author where bz_id < 30001');
Note that the SQL keyword "select" needs to be omitted from the above
SQL statement string when using the select() method. insert / update / delete
The insert, update() and delete() methods returns
the number of affected rows: $n= $conn->insert('option_matrix (contract_id, option_id) values (10, 501)');
Exceptions
All methods will throw exceptions for any errors encountered during their
operation. All these exceptions are subclasses of SQLException,
so to catch all possible errors, use it in the catch clause. try { If you want to distinguish between the different cases, you can do so in a quite fine-grained way: try {
Preparing statements
In all of the above examples, you notice all the SQL is unparametrized. In most
usecases, you'd want to pass parameters to the statements though. To "bind"
parameters to an SQL query, all of the afforementioned methods offer a printf
style tokenizer and support varargs syntax. These take care of NULL and proper
escaping for you. // Selecting
TokensThe following tokens are recognized: In addition to the format token, the following rules apply:
Transactions
To start a transaction, you can use the connection's begin method. It
will return a Transaction instance. public function createAuthor(...) {
Note: Not all RDBMS' support transactions, and of those that do, not all
support nested transactions. Be sure to read the manual pages of the RDBMS
you are accessing. Logging
When working with databases, it is most common to be log the client/server
communication, especially during development. The database API integrates
with the util.log package to support this. If you
already have a logger set up, it is as easy as modifying the connection
string: $conn= DriverManager::getConnection('mysql://localhost/NEWS?log=default');
To set up a logger category, use the following: Logger::getInstance()->getCategory()->addAppender(new FileAppender('debug.log'));
If you want to split usual debug output from SQL logging, you can use a
different logger category: // Add a FileAppender logging to sql.log for the "sql" category
The connection manager
Often it is necessary to use database connections in various places within
sourcecode. Imagine a database-driven web application such as a weblog, forum,
or even a configuration suite (such as 1&1's control panel). In either of
the aforementioned you will probably use the database connection in state
classes (the ones reflecting a page or a set of pages), in handlers (the
classes handling submitted data), in helper classes, and maybe in even more
places. ConnectionManager::getInstance()->register( ...or by using a configuration file: ConnectionManager::getInstance()->configure(
For the latter case, the property file etc/connections.ini needed
will look like this: ; Database configuration [caffeine] dsn="sybase://user:pass@server/CAFFEINE?autoconnect=1"
Note: It is generally a good idea to use the property file approach: This
way, no database credentials exist in the sourcecode. $conn= ConnectionManager::getInstance()->getByHost('caffeine', 0);
| Table of contents |