大对象 (LOB)

应用程序在某一时刻,可能需要在数据库中存储对象。大对象本质上可能是文本或二进制。在 PDOStatement::bindParam()PDOStatement::bindColumn()) 调用中使用 PDO::PARAM_LOB 类型码可以让 PDO 使用大数据类型。PDO::PARAM_LOB 告诉 PDO 作为流来映射数据,以便能使用 PHP Streams API 来操作。

pdo_aci对于BLOB和CLOB类型,查询时默认是安装流方式返回的,无法直接获得结果,可以用stream_get_contents的方法获取数据。

一个简单的例子

从文件中读取数据写入神通数据库LOB列的编程示例如下:

<?php
$dsn = "aci:dbname=localhost:2003/osrdb;charset=ZHS16GBK";
$user = "sysdba";
$pass = "szoscar55";

$db = new PDO($dsn, $user, $pass);
$db->exec('CREATE TABLE test (id int NOT NULL PRIMARY KEY, val BLOB)');

$fp = tmpfile();
fwrite($fp, "I am the LOB data");
rewind($fp);

$db->beginTransaction();
$insert = $db->prepare("insert into test (id, val) values (1, EMPTY_BLOB()) RETURNING val INTO :blob");
$insert->bindValue(':blob', $fp, PDO::PARAM_LOB);
$insert->execute();
$insert = null;
$db->commit();
?>

获取CLOB数据

对于CLOB类型,有三种获取方式:

第一种:流方式,这也是默认方式,需要用stream_get_contents的方法具体数据;

<?php
# create table demo ( a int ,b clob);
# insert into demo values(1,'abc');
$db=new PDO('aci:dbname=localhost:2003/osrdb','sysdba','szoscar55');
$sql='select *  from  demo';
$rs=$db->query($sql);
while ($row=$rs->fetch()){
           var_dump($row);
           var_dump(stream_get_contents($row['B']));
}
?>

执行结果

array(4) {

["A"]=>

string(1) "1"

[0]=>

string(1) "1"

["B"]=>

resource(4) of type (stream)

[1]=>

resource(4) of type (stream)

}

string(3) "abc"

第二种:使用PDOStatement::bindColumn()方法来指定通过其他方式返回,比如CLOB按照字符串方式返回时,设置如下:

$stmt->bindColumn(2, $lob, PDO::PARAM_STR); #虽然第二列为LOB,但指定PARAM_STR方式
<?php
# create table demo ( a int ,b clob);
# insert into demo values(1,'abc');
$db=new PDO('aci:dbname=localhost:2003/osrdb','sysdba','szoscar55');
$stmt = $db->prepare("select *  from  demo");
$stmt->execute();
$stmt->bindColumn(1, $type, PDO::PARAM_INT);
$stmt->bindColumn(2, $lob, PDO::PARAM_STR);
while ($stmt->fetch(PDO::FETCH_BOUND)){
    print_r("lobdata:",$lob);
}
?>

执行结果

lobdata:abc

第三种:在连接字符串中设置lob2str选项,如果lob2str的值为非0,则代表用CLOB数据默认以字符串方式返回。需要注意的是这种方式返回数据的长度有限制(默认150000字节),可在连接字符串中添加选项进行设置:

比如设置可以查询1M的数据:aci:dbname=localhost:2003/osrdb?dbtext_max_len=1048576

用例如下:

<?php
# create table demo ( a int ,b clob);
# insert into demo values(1,'abc');
$db=new PDO('aci:dbname=localhost:2003/osrdb?dbtext_max_len=1048576;lob2str=1','sysdba','szoscar55');
$sql='select *  from  demo';
$a=$db->query($sql);
while ($row=$a->fetch()){
    var_dump($row);
}
?>

执行结果

array(4) {

["A"]=>

string(1) "1"

[0]=>

string(1) "1"

["B"]=>

string(3) "abc"

[1]=>

string(3) "abc"

}