<%
一些asp开发过程中常用的数据操作,整理成了函数,提高开发效率
webdir="test/" 路径,根据实际情况修改
function conndb(connname)连接数据库
set connname=server.createobject("adodb.connection")
connname.open "driver={microsoft access driver (*.mdb)};dbq="&server.mappath(webdir & "inc/mydb.mdb")
connname.open "provider=sqloledb;server=192.168.0.1;uid=sa;pwd=;database=test" 使用sql server数据库时
end function
function close(objectname) 关闭对象
objectname.close
set objectname=nothing
end function
function creaters(rsname) 创建数据集对象
set rsname=server.createobject("adodb.recordset")
end function
function getvalue(thisvalue)
getvalue=trim(request(thisvalue))
end function
以下函数形参定义解释
rsname为定义数据集对象,dataname为表名,fields为要获取的字段名称(以逗号隔开,空为所有)
where为条件,order为排序方式
eg:call readdb(rs,"tablename1","id,name,sex","sex=男 and id>10","id desc")
返回:记录集对象
sub readdb(rsname,dataname,fields,where,order) 读取记录
dim source,recrsname,mok
if trim(fields)="" then fields=" * "
source="select "&fields&" from "&dataname
if trim(where)<>"" then source=source&" where "&where
if trim(order)<>"" then source=source&" order by "&order
set recrsname=server.createobject("adodb.recordset")
recrsname.open source,conn,3,1
set rsname = recrsname
end sub
function countnumber(tablename,where)获得表中满足条件的记录数
if len(trim(where))>0 then
thiswhere=" where " & where
else
thiswhere=""
end if
set rs=conn.execute("select count(*) as thisnumber from " & tablename & thiswhere)
thisnumber=rs("thisnumber")
close rs
countnumber=thisnumber
end function
function insertdb(dataname,field) 增加,插入一条新记录,要求提交表单项名称与数据表中的字段名称统一。
dim insertrs,i,datafield,datafieldvalue
datafield=split(field,",")
set insertrs=server.createobject ("adodb.recordset")
insertrs.open dataname,conn,1,3
insertrs.addnew
for i=0 to ubound(datafield)
datafieldvalue=getvalue(datafield(i))
if len(datafieldvalue)=0 then
datafieldvalue=" "
end if
insertrs(datafield(i))=datafieldvalue
next
insertrs.update
close insertrs
end function
function modifydb(dataname,field,where) 修改满足条件的记录。
if trim(field)="" then
fields=" * "
else
fields=field
end if
source="select "&fields&" from "&dataname
if trim(where)<>"" then source=source&" where "&where
datafield=split(field,",")
set insertrs=server.createobject ("adodb.recordset")
insertrs.open source,conn,3,2
while not insertrs.eof
for i=0 to ubound(datafield)
datafieldvalue=getvalue(datafield(i))
insertrs(datafield(i))=datafieldvalue
next
insertrs.update
insertrs.movenext
wend
close insertrs
end function
function deletedb(dataname,where)删除记录
dim delsql
delsql="delete from "&dataname
if trim(where)<>"" then delsql=delsql&" where "&where
conn.execute delsql
end function
%>
