日期:2009-10-26  浏览次数:20848 次

通用网页查询函数的功能主要是:根据调用者提供的各种参数,在后台数据库管理系统中进行检索,最后将检索结果以二维数组的形式返回给调用者。
为了实现上述功能,实现该函数的主要思想是:根据调用者提供的各种参数,生成对应的SQL语句,接下来与后台数据库管理系统建立连接、提取数据、断开连接,最后将检索结果以二维数组的形式返回给调用者。

该函数的输入参数有:后台数据库管理系统的代号(如0代表SQLServer、1代表VFP等)、数据源名、表名(可以是单表,也可以是多表连接)或视图名、all/distinct关键字、top关键字、字段名数组、where条件、group by子句/order by字句、检索结果存放的二维数组名等。
该函数的返回值为逻辑型,True代表查询过程中未出现错误,否则,若为False说明查询过程中出现了错误。
下面给出经调试过的通用网页查询函数的源代码。
function data_getting(param_database_code,param_dsn_name,param_table_name,
param_all,param_top,param_field_names(),ByRef data(),param_condition,
param_other,ByRef rcount,ByRef fcount,ByRef fieldsname())
on error resume next
'生成查询语句
if param_all=true then
query="select "
else
query="select distinct "
end if
query=query+param_top+" "
if param_field_names(0)="*" then '查询全部字段
query=query+" * "
else
d_g_i=0
fcount=0
for each item in param_field_names
if param_field_names(d_g_i)<>"" then
query=query+param_field_names(d_g_i)+","
fcount=fcount+1 '记录集列数
end if
d_g_i=d_g_i+1
next
end if
query=left(query,len(query)-1)+" from "+param_table_name '去掉最后一个逗号(全部字段:去掉空格)
if len(param_condition)>0 then
query=query+" where "+param_condition
end if
if len(param_other)>0 then
query=query+" "+param_other
end if

'打开记录集
set conntemp=server.createobject("ADODB.Connection")
conntemp.ConnectionString=param_dsn_name
conntemp.Open
conntemp.errors.clear
Set rstemp=Server.CreateObject("ADODB.Recordset")
rstemp.ActiveConnection=conntemp
if param_database_code=0 then ‘代表后台数据库是SQLSERVER
rstemp.CursorType=3
rstemp.LockType=1
else if param_database_code=1 then ‘代表后台数据库是VFP
rstemp.CursorType=1
rstemp.LockType=1
else
… ‘代表后台数据库是其它数据库管理系统(代码略)
end if
rstemp.Source=query
rstemp.open

‘判断查询过程中是否出现错误
if conntemp.errors.count>0 then
data_getting=false
rcount=0
else
‘如果查询过程中未出现错误,将查询结果存放到指定的二维数组中
rcount=rstemp.recordcount '记录集行数
if rcount=0 then
data_getting=true
else
data_getting=true
if param_field_names(0)="*" then '查询全部字段
fcount=rstemp.fields.count
end if
ReDim data(rcount-1,fcount-1),fieldsname(fcount-1)
for d_g_i=1 to rcount
for d_g_j=1 to fcount
data(d_g_i-1,d_g_j-1)=trim(rstemp.fields(d_g_j-1).value)
if d_g_i=1 then
fieldsname(d_g_j-1)=rstemp.fields(d_g_j-1).name
end if
next
rstemp.movenext
next
end if
end if
rstemp.close
set rstemp=nothing
conntemp.close
set conntemp=nothing
end function
3. 通用网页查询函数的应用
在笔者参与的各类基于Web的数据库应用系统的开发过程中,全部使用了前文给出的通用网页查询函数。利用<!-- #include file="data_getting.inc" -->语句(通用网页查询函数被保存为一个独立的文件data_getting.inc),在需要进行数据查询的网页中,嵌入该函数,然后在ASP页面只需调用该函数,就能得到希望得到的查询结果,从而大大减轻了编程的工作量,并便于ASP页面的简化和美化。
4. 结束语
本文给出的通用网页查询函数,以及笔者开发的其它的一些通用函数(用于执行一系列SQL命令的函数、用于调用数据库端存储过程的函数等),大大减轻了在系统开发过程中的工作量,基本实现了代码复用的目的,希望能给从事数据库应用系统的开发者一些有益的启示。