日期:2012-08-16  浏览次数:21027 次

<%
''一些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
%>