// convert $timeout to the MDB timestamp format
$timeout = MDB_date::unix2Mdbstamp($timeout);
// SELECT query showing how the datatype conversion works
$query = 'SELECT createtime, user_id FROM sessions';
$query .= ' WHERE session = '.$mdb->getTextValue($session);
$query .= ' AND lastaccess < '.$mdb->getTimestampValue($timeout);
For the sake of the example let us assume that we only want to retrieve the first row. MDB::queryRow() fetches the first row, he frees the result set and returns the content, so it is exactly what we want.
为了作个演示,让我们假定我仅仅想要获取第一行。MDB::queryRow() 获得第一行,它释放结果集并且返回其内容,因而它正是我们所要的。
$result = $mdb->queryRow($query);
But different RDBMS return data like dates in different formats. So, if I then want to do some date arithmetic it is important that data is always returned in the same format regardless of the RDBMS chosen. This can be done semi-automatically by MDB. All you need to do is tell MDB what type your result columns will have and MDB handles the conversion. The easiest way is to pass such information with the query method call:
但是不同的 RDBMS 返回像日期这样的数据时用的格式是不同的。因此,如果我们然后要对一些数据进行计算,不管选择的 RDBMS 是什么,把数据以相同的格式返回是重要的。这个可以由 MDB 半自动地完成。你所有需要做的是告诉你的结果列将是什么样的类型,MDB将处理转换的工作。最简单的办法是把这样的信息传递给查询函数。
$types = array('timestamp', 'integer');
$result = $mdb->queryRow($query, $types);
This tells MDB that the first column of the result set is of the type `timestamp' and the second is of the type `integer'. All methods that allow querying can take such meta-information as an optional parameter. The data can also be set later using MDB::setResultTypes(). Depending on the database that the data is retrieved from, it will then convert the returned data accordingly. The MDB internal data format for timestamps is the ISO 8601 standard. Other packages such as PEAR::Date can handle this format. MDB also provides a small number of methods for date format conversion in the MDB_Date class that can be included optionally.
这告诉 MDB 结果集的第一列类型是 'timestamp' 以及第二列是'integer'。所有查询函数能够接受这样的元信息作为可选的参数。数据还能事后用 MDB::setResultTypes() 来设置。取决于数据获取于的数据库,它然后将被相应的转换返回的数据。MDB 内部的 timestamps 的数据格式是遵循 ISO 8601 标准的。其他像 PEAR::Date 这样的包能够处理这种格式。MDB 还在 MDB_Date 类中提供了一些数据格式转换函数,它们能够被可选的包含。
Since pretty much every RDBMS returns integer data the same way there is no need to convert integer data. So, in order to gain a slight performance improvement you could do the following:
因为相当多的 RDBMS 以相同的方法返回整数数据,没有必要转换整数数据。因而,为了获得稍许的性能改进你能够这么做:
$types = array('timestamp');
$result = $mdb->queryRow($query, $types);
This way only the first column of the result set would be converted. Of course this may become an issue if MDB would be used in conjunction with a database that does return integers differently. However unlikely, the slight performance increase might not be worth this risk. But again it shows that the usage of these features is optional.
这样只有结果集的第一列会被转换。当然,如果 MDB 用于返回整数不同的数据库,这可能成为一个问题。然而,稍许的性能改善可能并不值得冒这个风险。但是再一次的,它显示了这些特性的使用仅仅是供选择的。
Listing 1 shows an example use of prepared queries. These can be quite convenient if you have to run a number of queries where the only difference is in the data that is being passed to the database while the structure of the query remains the same. Advanced databases can store the parsed query in memory to offer a performance boost.
Listing 1 展示了一个使用预准备的查询的例子。如果你必须运行大量查询而唯一的差别是数据传递给数据库,但是查询的结构还是一样的,这些能够相当的方便。高级的数据库能够在内存中储存解析好的查询来加速性能。
Listing 1
$alldata = array(
array(1, 'one', 'un'),
array(2, 'two', 'deux'),
array(3, 'three', 'trois'),
array(4, 'four', 'quatre')
);
$p_query = $mdb->prepareQuery('INSERT INTO numbers VALUES (?,?,?)');
$param_types = array('integer', 'text', 'text');
foreach ($alldata as $row) {
$mdb->execute($p_query, NULL, $row, $param_types);
}
Each of the 4 arrays that are stored in $alldata will be used in an execute statement. The data will automatically be converted to the correct format. Since this is an insert statement the second parameter for MDB::execute() is set to NULL because we will not have any result columns for which we would need to set data types.
在 $alldata 中储存的所有四个数组将用于 execute 语句。数据将自动被转换为正确的格式。因为这是一个插入语句,MDB::execute() 的第二个参数被设置为 NULL 因为我们将没有任何结果列需要我们设置数据类型。
Among the supported data type are also LOB's (Large OBjects) which allow you to store files into a database. Binary files are stored in BLOBs (Binary Large OBject) and normal text files are stored on CLOBs (Character Large OBject). In MDB you can only store LOB's using prepared INSERT and UPDATE queries. Using either MDB::setParamBlob() or MDB::setParamClob() you can set the values of the LOB field in a prepared query. Both methods expect to be passed a LOB object however which can be created using MDB::createLob().
在支持的数据类型中还有 LOB (大对象),它使得我们能够在数据库中储存文件。二进制文件储存在 BLOB (二进制大对象)中而且普通文本文件储存在 CLOB (字符大对象)中。在 MDB 中你仅仅能够使用预准备的 INSERT 和 UPDATE 查询储存 LOB。使用 MDBA::setParamBlob() 或者 MDB::setParamClob() 你能够设置预准备查询的 LOB 域的值。两个函数都预期传递一个 LOB 对象,而它能够使用 MDB::createLob() 创建。
$binary_lob = array(
'Type' => 'inputfile',
'FileName' => './myfile.gif'
);
$blob = $mdb->createLob($binary_lob);
$character_lob = array(
'Type' => 'data',
'Data' => 'this would be a very long string container the CLOB data'
);
$clob = $mdb->createLob($character_lob);
As you can see MDB::createLob() is passed an associative array. The value for the Type key may be one of the following: data, inputfile or outputfile. The first two are used when you want to write a LOB into the database. If you have the LOB stored in a variable you should use data while inputfile should be used to read the LOB directly from a file. Finally, outputfile should be used when you want to retrieve a LOB from the database. Depending on if you are using data or inputfile you need to specify a value for the Filename key or the Data key as seen in the above example. Now, we will store the above LOB's in the database.
如你能看到的,MDB::createLob() 被传递一个关系数组。Type 键的值可能是以下中的一个:data, inputfile 或者 outputfile。前两个用于你想要把 LOB 写入数据库的时候。如果你有一个储存在变量中的 LOB,你应当在 需要使用 inputfile 时从文件直接读取 LOB。最后,outpufile 应当在你想要从数据库中读取 LOB 时使用。取决于你是否使用数据或者 inputfile 你需要给 Filename 键或者 Data 键指定一个值,像上面的例子那样。现在,我们将把前面的 LOB 储存到数据库中去。
$p_query = $mdb->prepareQuery('INSERT INTO files (id, b_data, c_data) VALUES (1, ?, ?)');
$mdb->setParamBlob($p_query, 1 , $blob, 'b_data');
$mdb->setParamClob($p_query, 2 , $clob, 'c_data');
$result = $mdb->executeQuery($p_query);
In order to fetch the above file from the database we will need to first select the data from the database and create a LOB object using MDB::createLob(). This time we will set `Type' to `outputfile'.
为了从数据库中获取上面的文件,我们需要首先从数据库中选择数据并且使用 MDB::createLob() 创建 LOB 对象。这次我们将设置 'Type' 为 'outputfile'
$mdb->query('SELECT b_data FROM files WHERE id = 1');
$binary_lob = array(
'Type' => 'outputfile',
'Result' => $result,
'Row' => 0,
'Field' => 'b_data',
'Binary' => 1,
'FileName' => './myfile2.gif'
);
$blob = $mdb->createLob($binary_lob);
Now we can read the LOB from the result set using MDB::readLob(). Passing a length of 0 to MDB::readLob() means that the entire LOB is read and stored in the file we specified above. Once we are done we can free the resources. Alternatively, you can set any length larger than zero and read the LOB using a while loop checking MDB::endofLob().
现在我们能够使用 MDB::readLob() 从结果集中读取 LOB。传递长度 0 给 MDB::readLob() 意味着整个 LOB 被读取和储存在我们前面指定的文件中。一旦任务完成了,我们可以把资源释放了。你也可以设置任何大于零的长度并且使用一个 while 循环检查 MDB::endofLob() 来读取 LOB。
$mdb->readLob($blob, $data, 0);
It is important to note that you may not mix this method of fetching with the bulk fetching methods like MDB::fetchAll() as this will cause problems in most PHP database extensions. At some point MDB may be able to retrieve LOB's using the bulk fetching methods.
注意你不要把这个获取函数和 bulk 获取函数像 MDB::fetchAll()搞混了,因为这将在大部分 PHP 数据库扩展中导致问题。在一些时候,MDB 可能能够使用 bulk 获取函数获得 LOB。
As we have seen in this section MDB features its own set of native data types that are automatically mapped to native data types in the database. This ensures that no matter what data we send or retrieve from the database it will always be in the same format no matter what RDBMS is used. As I have mentioned in the opening paragraph of this section this obviously requires that the data types used in the database are what MDB expects. This requirement was made to ensure that the mapping is done with a minimal performance loss. The next section will teach us how MDB assists with using the correct data types in the database.
如我们在这节所见,MDB 特性本身的原生数据类型集自动映射于数据库中的原生数据类型。这保证了无论我们发送和从数据库接收什么样的数据,它都能与使用的 RDBMS 无关的使用相同的格式。如我在本节开篇已经提到的,这明显需要数据库使用的数据类型是 MDB 预期的。这种需要被用于确保映射所耗费的代价很小。下一节将教给我们 MDB 如何辅助在数据库中使用正确的数据类型。
Making use of XML schema files
使用 XML schema 文件
With the features described in the last paragraph you can write truly database independent applications. But MDB tries to go one step further: It allows you to define your schemas in XML. A manager converts this schema into the necessary SQL statements for each RDBMS. This means that you can use the same schema for any of the supported RDBMS. The examples for this section can be found in the xml_schema directory.
利用在上个段落中描述的特性,你能编写真正的数据库独立的程序。但是 MDB 尝试向前更加迈出一步:它允许你用 XML 定义你的 schema。一个管理器把这种 schema 转换为给每种 RDBMS 的必要的 SQL 语句。这意味着你能对所有支持的 RDBMS 使用相同的 schema。本节的例子能够在 xml_schema 目录中找到。
We will now write an XML schema file from scratch. First we must define an XML document. The database definition is contained within a database tag. Th