bind_param 方法来指定 { db2_file => 1} 参数属性。
在我们的数据库模式 POT 下面有一个表 MAP。这个表有一个 picture 列,他被声明成 BLOB 类型的,用来存放某个地区的图像。下面是创建该表所使用的 DDL:
清单 22. 创建 MAP 表使用的 DDL
create table POT.MAPS
( map_id INT,
map_name VARCHAR(13),
area INT ,
photo_format CHAR(3),
picture BLOB) ;
|
另外,我们更有一个文档 pearcson.jpg,其中包含了 Pearson Airport 的地图。
图 3. 示例地图
现在让我们来编写一个程式,向表 POT.MAP 中插入一行数据,即将 JPG 文档的图像插入到 PICTURE 中。首先,需要构造一个具备 5 个参数标记的动态 SQL 语句。然后,需要对这条语句进行准备。在将参数绑定到准备好的语句上之前,需要指定包含要插入的图像的文档名,并将其赋给一个本地 Perl 变量($picture_file)。现在能够将任何参数全部绑定到需要插入到 MAP 表中的值上。请注意,我们为最后一个参数指定了 db2_file =>1 属性。最后一个步骤是执行这条 INSERT 语句。这个程式的代码如下:
清单 23. 插入 LOB
#!/usr/bin/perl -w
use DBI;
use DBD::DB2::Constants;
%conattr = ( AutoCommit => 1,
# Turn Autocommit On
db2_info_applname => 'Maps Module', );
# Identify this appl
$dbh = DBI->connect("dbi:DB2:sample","", "",\%conattr) or die "$DBI::errstr";
$dbh->do("SET CURRENT SCHEMA POT");
$sql = "INSERT INTO MAPS(map_id, map_name, area, photo_format, picture)
VALUES(?,?,?,?,?)";
$sth = $dbh->prepare($sql);
$picture_file = "pearson.jpg"; # File containing our picture
$sth->bind_param(1, 100); # map_id
$sth->bind_param(2, "Pearson airport"); # map_name
$sth->bind_param(3, 416); # area
$sth->bind_param(4, "JPG"); # photo_format
$sth->bind_param(5, $picture_file, {db2_file => 1});
$rows_affected = $sth->execute();
printf("%d rows affected", $rows_affected);
$sth->finish();
$dbh->disconnect;
|
从数据库中读取 LOB 数据
能够使用标准的 fetch 方法来检索 LOB 数据,例如 fetchrow_array 或 fetchrow_arrayref。DBI 让我们能够使用 LongReadLen 连接属性来配置每次 fetch 能够检索的最大字节数。对于 LOB 列来说,缺省值为 32,700 个字节。要实现这种功能,需要执行以下步骤:
- 构造 SQL 语句从 MAP 表中选择 picture 列的数据。
- 准备 SQL 语句。
- 为保存所检索到的图像使用的文档分配一个名字。
- 打开该文档。
- 执行这条 SQL 语句。
- 使用 fetch 方法将结果取到文档中。
下面是展示如何从数据库中检索 LOB 数据的代码:
清单 24. 从数据库中读取 LOB 数据
#!/usr/bin/perl
use DBI;
use DBD::DB2::Constants;
%conattr =
(
AutoCommit => 1,
# Turn Autocommit On
db2_info_applname => 'Maps Module',
# Identify this appl
LongReadLen => 80000
# Don't retrieve LOBs
);
# Connect to our database
$dbh = DBI->connect("dbi:DB2:sample","", "",\%conattr) or
die "$DBI::errstr";
# Set the current schema to 'POT'
$dbh->do("SET CURRENT SCHEMA POT");
$sql = "SELECT picture FROM maps WHERE map_name ='Pearson airport'";
# Prepare the statement
$sth = $dbh->prepare($sql);
# Open output file
$out_file = "mypic.jpg";
open(OUTPUT, ">$out_file") or die "Cannot open $out_file because $!";
binmode OUTPUT;
$sth->execute;
@row = $sth->fetchrow;
print OUTPUT $row[0];
@row = "";
close(OUTPUT);
print “Picture in the file $out_file\n";
$sth->finish();
$dbh->disconnect;
|
文章整理:西部数码--专业提供域名注册、虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!