Google
搜索WWW 博客内搜索
第一课.用ASP实现网上“五子棋”大赛

“五子棋”是大家都非常熟悉的一种益智类游戏,相关的游戏软件也非常多,在此我向大家隆重推出一款新的纯“网络版”的五子棋,它利用ASP做为开发环境,因此在Internet上对战的时候无需下载客户端软件,只要你有一个浏览器就可以了。你也可以在局域网上进行这个游戏。
对于ASP,我不想做过多的说明,在以前的文章中,我已经说过很多。
游戏的过程是这样的,我们首先登录,然后可以选择战场,有“金星”、“木星”、“水星”、“火星”、“土星”等五个战场,如果你自认为是一个高手,可以选择金星,否则可以依次选择其它几个星球做为战场。如果这个星球上没有擂主,你就应该以擂主的身份进入,然后别人就可以和你进行对战了。当然,如果所有的星球上都已经开始了战争,那么你就只能等一会儿了。
如果你是以擂主身份进入的,你可以等待别人来和你对战,如果你是以攻擂手的身份登录,你可以很快的和擂主展开战斗。开始战斗后,由擂主执黑先行,然后由攻擂手出招,如此这般。当最后决出胜负的时候,会有相应的提示。
该站点有几个主要的文件是:
Index.asp 登录文件:
Index0.asp中间文件:
Match.asp 比赛文件:
Back0.jpg white0.jpg black0.jpg 中间用到的图形文件,分别指的棋盘,白子和黑子,如下图:
在程序的初始化的时候,将棋盘上分成若干的表格,将背景图片放入其中,形成一个棋盘,然后在放上一个棋子后,再将图片换上相应的白子或黑子就可以了。
先看看登录文件:
<%@ Language=VBScript %>
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<title>星球大战之“五子连珠”大赛!</title>
</HEAD>
<BODY>
 
<p align=center><font size=6>星球大战</font></P>
<table border=1 width=80% align=center>
<tr><td>星球</td><td>擂主</td><td>大战</td><td>攻擂</td></tr>
<tr>
<td>金星</td>
<td>
<%
if application("first1")="" then
%>
<form action=index0.asp?flag=First1 method=post>
<INPUT id=text1 name=txtFirst1 size=10><INPUT id=submit1 name=submit1
type=submit value=进入>
</form>
<%
else
response.write application("first1")
end if
%>
</td>
<td>大战</td>
<td>
<%
if application("second1")="" then
%>
 
<form action=index0.asp?flag=second1 method=post>
<INPUT id=text1 name=txtSecond1 size=10><INPUT id=submit1
name=submit1 type=submit value=进入>
</form>
<%
else
response.write application("Second1")
end if
%>
</td>
</tr>
 
<tr>
<td>木星</td>
<td>
<%
if application("first2")="" then
%>
<form action=index0.asp?flag=First2 method=post>
<INPUT id=text1 name=txtFirst2 size=10><INPUT id=submit1 name=submit1
type=submit value=进入>
</form>
<%
else
response.write application("first2")
end if
%>
</td>
<td>大战</td>
<td>
<%
if application("second2")="" then
%>
 
<form action=index0.asp?flag=second2 method=post>
<INPUT id=text1 name=txtSecond2 size=10><INPUT id=submit1
name=submit1 type=submit value=进入>
</form>
<%
else
response.write application("Second2")
end if
%>
</td>
</tr>
 
<tr>
<td>金星</td>
<td>
<%
if application("first3")="" then
%>
<form action=index0.asp?flag=First3 method=post>
<INPUT id=text1 name=txtFirst3 size=10><INPUT id=submit1 name=submit1
type=submit value=进入>
</form>
<%
else
response.write application("first3")
end if
%>
</td>
<td>大战</td>
<td>
<%
if application("second3")="" then
%>
 
<form action=index0.asp?flag=second3 method=post>
<INPUT id=text1 name=txtSecond3 size=10><INPUT id=submit1
name=submit1 type=submit value=进入>
</form>
<%
else
response.write application("Second3")
end if
%>
</td>
</tr>
 
<tr>
<td>金星</td>
<td>
<%
if application("first4")="" then
%>
<form action=index0.asp?flag=First4 method=post>
<INPUT id=text1 name=txtFirst4 size=10><INPUT id=submit1 name=submit1
type=submit value=进入>
</form>
<%
else
response.write application("first4")
end if
%>
</td>
<td>大战</td>
<td>
<%
if application("second4")="" then
%>
 
<form action=index0.asp?flag=second4 method=post>
<INPUT id=text1 name=txtSecond4 size=10><INPUT id=submit1
name=submit1 type=submit value=进入>
</form>
<%
else
response.write application("Second4")
end if
%>
</td>
</tr>
 
<tr>
<td>金星</td>
<td>
<%
if application("first5")="" then
%>
<form action=index0.asp?flag=First5 method=post>
<INPUT id=text1 name=txtFirst5 size=10><INPUT id=submit1 name=submit1
type=submit value=进入>
</form>
<%
else
response.write application("first5")
end if
%>
</td>
<td>大战</td>
<td>
<%
if application("second5")="" then
%>
 
<form action=index0.asp?flag=second5 method=post>
<INPUT id=text1 name=txtSecond5 size=10><INPUT id=submit1
name=submit1 type=submit value=进入>
</form>
<%
else
response.write application("Second5")
end if
%>
</td>
</tr> 
</table>
</BODY>
</HTML>

这个文件不用做过多的说明,就是一个大的表格,大家可以从那里进入,如果某个位置已经被使用,则它会变成该大 侠的名字,不允许重复登录。在登录后进入
index0.asp,这是一个中间交换文件,在里面进行一些变量的处理及赋值,然后再进入match.asp,进行正式的比赛。我们来看一下index0.asp的内容:
<%@ Language=VBScript %>
<%
if Request.Form("txt" & request.querystring("flag"))<>"" then
'response.write "in!" & ""
session("nice")=Request.Form("txt" & request.querystring("flag"))
'response.write session("nice") & ""
'response.write application(request.querystring("flag"))
if application(request.querystring("flag"))="" then
application(request.querystring("flag"))=session("nice")
session("class")=right(request.querystring("flag"),1)
if left(request.querystring("flag"),1)="f" then
application(session("nice"))=false
elseif left(request.querystring("flag"),1)="s" then
application(session("nice"))=false
application(application("first" & session("class")))=true
end if
Response.Redirect "match.asp"
end if
 
 
end if
 
%>
<HTML>
</HTML>

该程序中,用session(“nice”)来记录您登录的大名,以后的处理中,很多都要用到它,用它来区分很多的用户。如果您是从擂主的位置进入,则您的权利是
first,否则是second,用session("class")来记录位于哪个战场场,“金”“木”
“水”“火”“土”分别表示为1、2、3、4、5,因为有多个战场可能同时开战,如果不能正确地区分开,则可能导致一片混乱。application(session("nice"))是一个逻辑型变量,用真假来表示您是否可以出棋,如果是假,您要等待一个,如果是真,您就可以下棋了。只有一个战场上的两个人都进入了以后,擂主方可以下棋,而且只有当擂主出子以后,攻擂手才可以下棋。准备好以后,下面就进入赛场,请看文件match.asp


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<META http-equiv=refresh content=3>
<title>连珠大赛...</title>
</head>
<%
Response.Write "擂主:" & application("first" & session("class"))
& "    攻擂:" & application("second" & session
("class"))
if Request.QueryString("pos")<>"" then
application("pos" & session("class") & Request.QueryString("pos"))
=true
end if
%>
<body>
<%
'Response.Write application("aaa")
if application("first" & session("class"))=session("nice") then
color="black"
if Request.QueryString("pos")<>"" then
if session("last")="" then session("last")="abc"
if session("last")<> Request.QueryString("pos") then
application(application("first" & session("class")))=false
if application("second" & session("class"))<>"" then application
(application("second" & session("class")))=true
session("last")=Request.QueryString("pos")
END IF
end if
else
if application("second" & session("class"))=session("nice") then
color="white"
if Request.QueryString("pos")<>"" then
'if session("last")="" then session("last")="abc"
if session("last")<> Request.QueryString("pos") then
application(application("first" & session("class")))=true
application(application("second" & session("class")))=false
session("last")=Request.QueryString("pos")
END IF
end if
else
if application("second" & session("class"))="" then
application("second" & session("class"))=session("nice")
color="white"
if Request.QueryString("pos")<>"" then
if session("last")="" then session("last")="abc"
if session("last")<> Request.QueryString("pos") then
application(application("first" & session("class")))=true
application(application("second" & session("class")))=false
session("last")=Request.QueryString("pos")
END IF
end if
else
color=""
end if
end if
end if
Response.Write "<table width=400 height=400 border=0 cellspacing=0
cellpadding=0>"
for i=1 to 16
Response.Write "<tr>"
for j=1 to 16
if application("pos" & session("class") & cstr(i) & "_" & cstr(j))=""
then
application("color" & session("class") & "_" & Request.QueryString
("pos"))=color
Response.Write "<td width=25 height=25>"
'response.write application(application("first" & session("class")))
if application(session("nice"))=true then
response.write "<a href=match.asp?pos=" & cstr(i) & "_" & cstr(j)
& "><img border=0 src=back0.jpg width=25 height=25></a>"
else
response.write "<img border=0 src=back0.jpg width=25 height=25>"
end if
response.write "</td>"
else
Response.Write "<td width=25 height=25><img border=0 src=" &
application("color" & session("class") & "_" & cstr(i) & "_" & cstr
(j)) & "0.jpg width=25 height=25></td>" & chr(13)
end if
next
Response.Write "</tr>"
next
Response.Write "</table>"
'判断输赢
if application("first" & session("class"))=session("nice") then
m="black"
h="white"
else
h="black"
m="white"
end if
'横向判断"-"
for i=1 to 15
win=false
loss=false
five_me=0
five_he=0
for j=1 to 15
if application("color" & session("class") & "_" & cstr(i) & "_" & cstr
(j))=m then
five_me=five_me+1
five_he=0
elseif application("color" & session("class") & "_" & cstr(i) & "_" &
cstr(j))=h then
five_me=0
five_he=five_he+1
else
five_me=0
five_he=0
end if
if five_me=5 then
win=true
loss=false
exit for
elseif five_he=5 then
win=false
loss=true
exit for
end if
next
if win or loss then exit for
next
if win then
response.write "你赢了!"
application(application("first" & session("class")))=false
application(application("second" & session("class")))=false
end if
if loss then
response.write "对不起,你输了!"
application(application("first" & session("class")))=false
application(application("second" & session("class")))=false
end if
 
'列向判断"|"
for j=1 to 15
win=false
loss=false
five_me=0
five_he=0
for i=1 to 15
if application("color" & session("class") & "_" & cstr(i) & "_" & cstr
(j))=m then
five_me=five_me+1
five_he=0
elseif application("color" & session("class") & "_" & cstr(i) & "_" &
cstr(j))=h then
five_me=0
five_he=five_he+1
else
five_me=0
five_he=0
end if
if five_me=5 then
win=true
loss=false
exit for
elseif five_he=5 then
win=false
loss=true
exit for
end if
next
if win or loss then exit for
next
if win then
response.write "你赢了!"
application(application("first" & session("class")))=false
application(application("second" & session("class")))=false
end if
if loss then
response.write "对不起,你输了!"
application(application("first" & session("class")))=false
application(application("second" & session("class")))=false
end if
 
'斜向判断"/"
for i=1 to 11
win=false
loss=false
five_me=0
five_he=0
for j=i+4 to 1 step -1
if application("color" & session("class") & "_" & cstr(j) & "_" & cstr
(i+5-j))=m then
five_me=five_me+1
five_he=0
elseif application("color" & session("class") & "_" & cstr(j) & "_" &
cstr(i+5-j))=h then
five_me=0
five_he=five_he+1
else
five_me=0
five_he=0
end if
if five_me=5 then
win=true
loss=false
exit for
elseif five_he=5 then
win=false
loss=true
exit for
end if
next
if win or loss then exit for
next
if win then
response.write "你赢了!"
application(application("first" & session("class")))=false
application(application("second" & session("class")))=false
end if
if loss then
response.write "对不起,你输了!"
application(application("first" & session("class")))=false
application(application("second" & session("class")))=false
end if
 
'斜向判断"\"
for i=1 to 11
win=false
loss=false
five_me=0
five_he=0
for j=12-i to 15
if application("color" & session("class") & "_" & cstr(13-i-j) & "_"
& cstr(j))=m then
five_me=five_me+1
five_he=0
elseif application("color" & session("class") & "_" & cstr(13-i-j)
& "_" & cstr(j))=h then
five_me=0
five_he=five_he+1
else
five_me=0
five_he=0
end if
if five_me=5 then
win=true
loss=false
exit for
elseif five_he=5 then
win=false
loss=true
exit for
end if
next
if win or loss then exit for
next
if win then
response.write "你赢了!"
application(application("first" & session("class")))=false
application(application("second" & session("class")))=false
end if
if loss then
response.write "对不起,你输了!"
application(application("first" & session("class")))=false
application(application("second" & session("class")))=false
end if
%>
</body>
</html>
如果某点没有棋子,则加上一个超连接,根据擂主与攻擂手的区别放上一个不同颜色的棋子。最后的一段是用来判断输与赢,分为横,列和两个斜线方向。具体内容看一下就可以明白。
最后要说的一点就是global.asa ,这是站点上的一个核心文件,为了在退出棋局后,将位置留给别人,需要在sesison_onend中加入代码进行处理,如下:

<script language=vbscript runat = server>
sub application_onstart
session.timeout=1
end sub
sub session_onstart
if application("num")="" then
application("num")=0
end if
application("num")=application("num")+1
end sub
</script>
 
<script language=vbscript runat = server>
sub session_onend
if application("num")="" then
application("num")=0
end if
application("num")=application("num")-1
 
if application("first1")=session("nice") then
application("first1")=""
elseif application("second1")=session("nice") then
application("second1")=""
 
elseif application("first2")=session("nice") then
application("first2")=""
elseif application("second2")=session("nice") then
application("second2")=""
 
elseif application("first3")=session("nice") then
application("first3")=""
elseif application("second3")=session("nice") then
application("second3")=""
 
elseif application("first4")=session("nice") then
application("first4")=""
elseif application("second4")=session("nice") then
application("second4")=""
 
elseif application("first5")=session("nice") then
application("first5")=""
elseif application("second5")=session("nice") then
application("second5")=""
end if
for i=1 to 15
for j=1 to 15
application("color" & session("class") & "_" & cstr(i) & "_" & cstr
(J))=""
application("pos" & session("class") & cstr(i) & "_" & cstr(j))=""
next
next
application(session("nice"))=""
end sub
</script>
以上就是几个主要的文件,大家可以一试。什么,想做围棋?把棋盘改一下就可以了。
祝大家成功!
 
第二课.用ASP构建音乐服务器

---- 音乐服务器(Music Server)是指一个提供音乐在线服务的服务器,它包括高端提供门户服务的网站、Web数据库和低端的操作平台、硬件设施。目前,在Internet和Intranet上有不少这样的站点,特别是在一些高速宽带的局域网中(如校园网),音乐服务器给上网的朋友提供了休闲娱乐的好去处,同时也给网站带来了较高的访问率。
----像其他站点一样,音乐服务器包括网站和硬件两个部分。硬件性能和服务器效率是成正比的,因而如何构建网站才是一个音乐服务器的关键。从目前来看,网站基本有两种类型:一种是运行在Unix / Linux环境下,采用Perl / C / Php / Java 等作CGI编程语言;一种是运行在Win NT Server 平台上,采用ASP / WinCGI 作后台语言。前者运行效率高,但结构复杂,比较适合大型站点;后者编程难度相对较低,而且采用ODBC驱动接口,数据库连接方便,特别适合作音乐服务器。
----本文将以ASP 5.0为编程环境、Mircosoft Access 97为Web 数据库、Win NT Server 4.0为运行平台,举例说明音乐服务器的构建步骤。
----一个基本的音乐服务器包括音乐在线欣赏、音乐排行榜、音乐主题检索和音乐下载等四个部分。下面将主要从技术角度来讨论如何实现以上功能。
音乐主题数据库的规划
----音乐主题数据库是Web站点存储所需音乐资料的仓库,它的规划在很大程度上影响了整个网站的结构和效率。数据库中可以单独建成一张表单,也可以以主键和外键的形式建成多张表单。本例中为说明上的便利,建成如下单表框架: (music.mdb)
音乐在线欣赏
----在线欣赏是指客户端利用播放器播放服务器端的音乐文件。其原理是当客户端向服务器提交音乐选单后,服务器生成相应的.m3u文件,并将该文件通过Http协议下行至客户端;客户端将被激发调用相应的播放器执行该文件,从而实现了音乐在线欣赏功能。目前支持.m3u文件的播放器有Winamp、Realplayer G2、 Musicmatch等。当这些播放器软件被正确安装在客户端时,就可以自动播放.m3u文件。所以解决问题的关键在于后台如何生成.m3u文件并下行到客户端。以下利用ASP中内置的FileSystem组件给出一种解决方案,并给出相应程序。
<%
dim choose,path,mydb,myset,SQL,fs,mp3
‘##### 获得list.htm表单中选中的歌曲项
对应的id号,并赋给字串变量choose #####
choose=“("
for i=3 to request.form.count
choose=choose+request.form(i)+“,"
next
choose=left(choose,len(choose)-1)+“)"
‘##### 判断choose变量,如果不包含任何id号,
说明list.htm中没有选中任何歌曲,终止程序#####
if choose=“()" then
response.redirect(“list.htm")
response.end
end if
‘#####设置文件路径,需要把temp目录的权限设为
对internet匿名用户具有read & write 权限 #####
path=“E:\inetpub\wwwroot\temp\"
‘##### 创建文件对象 #####
Set fs = CreateObject(“Scripting.FileSystemObject")
Set mp3 = fs.CreateTextFile(path+“listen.m3u", True)
‘##### 创建数据库对象#####
set mydb=server.createobject(“adodb.connection")
mydb.open “music"
‘##### 检索数据库,获得歌曲信息 #####
SQL=“select mp3name,url from "&dbname&
“where id in "&choose
set myset=tdb.execute(SQL)
do while not myset.eof
‘##### 生成点播歌曲文件列表 #####
mp3.Write(“http://"+myset(“url")+chr(10))
myset.movenext
loop
‘##### 更新数据库中的当天点播次数和
总共点播次数 #####
SQL=“update music set click=click+1,
this=this+1 where id in "&choose
mydb.execute(SQL)
‘##### 取消对象 #####
set myset=nothing
mydb.close
set mydb=nothing
mp3.close
set mp3=nothing
‘##### 将该文件下载给用户#####
response.redirect(“listen.m3u")
response.end
%>

----注意:利用这种方法时,要控制.m3u文件Http头的内容。在Winnt中可利用IIS设置.m3u文件类型的Mine内容。具体操作如下:启动IIS —> 选中音乐服务器所在的Web站点 —> 点击“属性” 按钮 —> 在出现的属性选项卡中点击“Http标题”卡 —> 点击“文件类型”按钮 —> 点击“新增类型”按钮 —> 在“相应的扩展名”中填入“.m3u”,在“内容类型”中填入“audio/mpegurl” —> 然后一路确定即可。
音乐排行榜
----音乐排行榜是音乐服务器不可缺少的一项内容,其重要性不亚于一个站点的Pageview。它可以向歌迷即时提供信息、引导欣赏、动态地反映潮流趋势。在众多的音乐服务器中,排行榜也是竟相推陈出新的地方,具有很高的点击率。一般说来,排行榜包括总共点播次数、当天点播次数、总共下载次数等内容。具体的实现方法比较简单。在单表中可以利用如下SQL语句:select * from music order by total_click 。若是多表,则可以利用带join子句的联合查询SQL语句。如果要限定查询记录数,可采用count()集合函数。如在本例中,如果要查询当天点播次数前20名的歌曲,可采用如下语句:select top 20 * from music order by total_click desc 。排行榜的功能主要取决于主题数据库的规划如何,你可以根据需要增删字段,以实现相应功能(如增加进榜时间、歌手资料、名次变化等等),所涉及的SQL语句也不会过于复杂。总之,排行榜是体现一个音乐网站特色所在,可以自由发挥。
音乐主题检索
----提到检索,很多人立刻联想到Yahoo、Soho等著名站点,并且颇有神秘之感。其实,搜索引擎在数据库中并非难事,因为数据库内置的数据引擎已经提供了很好的基础。搜索效率的高低取决于数据库的性能和SQL语句的效率。在前台,可以提供一系列的检索项目和条件选项。在后台,则根据前台提交的表单,生成相应的查询语句在数据库中执行,并将查询结果返回。比如在前台提交的表单为:检索项目=“歌手姓名”,内容=“张学友”,匹配条件=“全字匹配”,则后台生成的SQL 语句为:select * from music where singer=‘张学友' order by edition,id asc,这样就可以检索出张学友的所有歌曲信息,并按专集分类返回。又如前台要查询的歌手姓名为“齐秦”,且歌曲名称带有“雨”字的所有歌曲(即要求模糊匹配),则后台生成的SQL语句为: select * from music where singer =‘齐秦' and mp3name like ‘%雨%' order by id asc ,将返回“冬雨”、“太阳雨”、“无情的雨无情的你”等等。只要运用适当的技巧和灵活的 SQL语句,就可以让你的主题检索发挥得淋漓尽致。
音乐下载功能
----提供音乐下载功能,同样是音乐服务器的一个基本功能,特别是对远程用户,将喜爱的歌曲下载后才能欣赏。一般有两种方式提供下载,一种是直接通过Http和浏览器下载,另一种是将曲库开辟为Ftp目录,通过ftp协议下载。本例中采用前一种方式,并且在数据库中对下载次数进行跟踪记录。有些站点还根据需要对歌曲进行压缩加密,将密码提供给正式用В彩且惶蹩扇≈馈1纠谐绦蛉缦拢?
<%
‘##### 获得歌曲标志号id #####
id=request(“id")
set tdb=server.createobject(“adodb.connection")
tdb.open “music"
SQL=“select mp3url from music where id ="&id
set tset=tdb.execute(SQL)
if tset.eof then
response.end
else
‘##### 更新数据库中歌曲的下载次数 #####
SQL=“update music set total_down=total_down
+1 where id ="&id
tdb.execute(SQL)
downfile=tset(“url")
tdb.close
set tset=nothing
set tdb=nothing
end if
if downfile=“" or isnull(downfile) then response.end
downfile=“http://"+downfile
‘##### 下载相应歌曲 #####
response.redirect(downfile)
response.end
%>

----以上步骤就构建了一个基本的音乐服务器。当然,一个完整的音乐服务器还可以包括歌手信息、歌迷论坛、聊天室、投票站、娱乐新闻网等等功能,都可以用ASP一一实现。本文限于篇幅,不再详细讨论。只要前台页面采用独特的风格设计和完善的JavaScript程序控制,后台编程运用灵活的SQL语句和强大的ASP组件,加之规划周到的Web数据库和丰富的创意,就能构建一个完美的音乐服务器。有兴趣的朋友不妨试试看,你会创造一个奇迹的!


第三课.在ASP中实现购物小车

为了讲解方便,突出重点,本文用数组实现要显示的商品信息。但在实际的系统开发中,这些商品信息的数据应该来自后台数据库。
  在程序中,我们定义了一个sp数组并对其赋值,然后用一个循环实现其数据显示及对下一个程序的数据传递。程序部分代码如下:
<% i=1
do while (i<=5) %>
<tr > <td><%=sp(i)%></td>
<td><a href=“cart.asp?spid=<%=sp(i)%>”>订购</a></td> </tr>
<% i=i+1
loop %>

   构建购物小车
  为处理用户订购商品的操作,我们自定义了两个Session的属性,分别是“spid”(用来保存商品名称)和“num”(用来保存相应商品的订购数量)。当用户订购了一种商品后,我们分三种情况对Session进行处理:
●购物小车为空,即Session(“spid")=“",直接将spid与num加入Session;
●购物小车非空且当前订购的商品是购物小车中没有的,则处理方法同上;
●购物小车非空但当前订购的商品是购物小车中已有的,Session保持不变。
程序实现的要点是如何判别当前订购的商品在购物小车中是否存在,因此,首先要将Session变量的内容拆分并存入数组:
array1=split(Session(“spid”),“:”)
然后用循环语句判别array1中是否有元素与传递来的spid相同并将结果存入变量ifbuy:
for i=0 to ubound(array1)-1
if array1(i)= Request.QueryString(“spid”) then
ifbuy=true
exit for
end if
next

将新增的商品信息加入Session:
Session(“spid”)=Session(“spid”)& Request.
QueryString(“spid”)&“:”
Session对象的另一个自定义属性num的处理同spid相同。
    购物小车的显示
  显示用户已经购买的商品信息,即是显示Session变量的内容。只要将Session变量的内容拆分,存入数组中,再显示数组的内容即可。购物小车的显示界面如图1所示,其中“数量”栏的类型为“text",“取消本商品”栏的类型为“checkbox”。这两栏的数据是可以变动的,在“取消本商品”栏中打“√”,再按“重新计算”,将在购物小车中取消该商品。

图1
“重新计算”和“继续购买”两个命令按钮用JavaScript实现:
<script language=“JavaScript">
<!--
function onback(theForm)
{window.history.back() }
function recal(theForm)
{theform.action=“modifycart.asp" }
-->
</script>

实现显示购物小车的代码如下:
<%
dim k
array1=split(Session(“spid”),“:”)
array2=split(Session(“num”),“:”)
k=0
do while k<ubound(array1) %>
<tr>
<td><p align=“center”><%=array1(k)%>
</p></td>
<td><p><input type=“text” name=“t1” size=“10” value=“<%=array2(k)%>”></p></td>
<td><p><input type=“checkbox” name=
“ifcancel” value=<%=k%> ></p></td></tr>
<% k=k+1
loop %>
<tr>
<td align=center height=“42” colspan=“2”>
<input type=“submit” name=“submit” value=“重新计算”
onclick=“return recal(this.form)”></td>
<td align=center height=“42” colspan=“3”>
<input type=“submit” name=“Submit” value=“继续购买”
onclick=“return onback(this.form)”></td>
</tr>

   购物小车的修改
  在用户点击“重新计算”按钮后,需要对购物小车的内容进行修改,包括对数量的修改和将被取消的商品从Session中删除。
  对于数量的修改,只要将文本框中被变动过的数据重新存入Session中即可:
<%
’首先将保存在Session变量中的订购数量提取出来
array=split(Session(“num”),“:”)
’将文本框t1中商品的数量提取出来,存入array数组中
if Request.Form(“t1”)<>“”then
Session(“num”)=“”
j=0
for each item in Request.Form(“t1”)
array(j)=item
j=j+1
next
’将提交后的商品数量放入Session变量中
for i=0 to ubound(array)-1
Session(“num”)=Session(“num”)&array(i)&“:”
next
end if %>

  要从Session中删除被选中的商品,首先要取得“checkbox”的返回值,它用来定位被取消的商品在Session变量中的位置。“checkbox”的返回值k是一个循环变量,是商品所在行的行数,其实也就是被选中商品在Session中的位置。如果不加返回值定义的话,“checkbox”的返回值是按自然数顺序排列的。例如,在图1所示的情况下,如果“电视机”和“书籍”两行被选中,若是“checkbox”不加返回值定义,它的返回值将分别为1和2,这样就会导致把“电视机”和“钢笔”从Session中删除的错误。
<% dim array1,array2,ifcancel(20),m1,m2,i,j
array1=split(Session(“spid”),“:”)
array2=split(Session(“num”),“:”)
m1=ubound(array1)-1
m2=ubound(array2)-1
’保存复选框checkbox的值
for i=1 to Request.Form (“ifcancel”).Count
ifcancel(i)=Request.Form (“ifcancel”)(i)
next
for i=1 to Request.Form (“ifcancel”).Count
’将checkbox选中的spid和num从Session中去掉
for j=ifcancel(j) to m1-1
array1(j)=array1(j+1)
array2(j)=array2(j+1)
next
’将总数减1,并将后面的checkbox的值减1
m1=m1-1
for p=i to Request.Form (“ifcancel”).Count
ifcancel(p)=ifcancel(p)-1
next
’将处理后的spid和num放回Session
Session(“spid”)=“”
Session(“num”)=“”
for j=0 to m1
Session(“spid”)=Session(“spid”)&array1(j)&“:”
Session(“num”)=Session(“num”)&array2(j)&“:”
next
next %>

  本文重点说明购物小车的实现与修改,所以对数据进行了简单化处理。在实际的商业系统中,对数据的处理要复杂得多,例如需要例外及安全验证等。

第四课.一个ASP统计制作实例

一个能对访问者进行编号、记录访问次数、IP、时间的统计制作实例
    我做了一个网站,www.zydn.net 当然啦,跟大家一样,也摆了个计数器在上面,每天看计数器都在不断的翻,心里很高兴,不过后来我又想,到底是谁看了我的网站啊?是新朋友还是老朋友啊?也不知他们来了多少次,我还想给他们都编上号,于是我申请了 免费统计,不过一连换了N个都不满意,唉,看来,只有自己动手才能丰衣足食了,说干就干,水平臭臭,还望高手笑话之于,不访指教。
    我以ACCESS库为例子,其实用SQL SERVER库也只要改一下链接库的语句就得啦,
库结构如下
库文件名: CONT.ASP 本来是CONT.MDB但在建好后把扩展名改为了ASP,以防库被下载。
表名:tab
字段名 数据类型 说明
ID 自动编号 访客的编号
IP 文本 用于记录访客的IP
dat1 日期时间 用于记录访客最后访问的时间
dat 日期时间 用于记录访客第一次访问的时间
CS 数字,整型 用于记录访客访问次数
程序很简单,只有两个文件,dispcont.asp 用于显示统计结果,contpage.asp用于统计信息,
先看看CONTPAGE.ASP 是乍么统计的,代码如下:
〈% Set Conn=Server.CreateObject("ADODB.Connection")
Connstr="DBQ="+server.mappath("cont.asp")+";DefaultDir=;DRIVER={Microsoft Access Driver (*.mdb)};"
Conn.Open connstr '*****以上语句用于连接库,cont.asp是库文件名。


keren=request.cookies("keren") '读取cookies,cookies的名为:“keren”,哈哈。。阿余的E文学的臭,只懂用拼音啦。
if keren="" then '判断cookees是不是空,如果是空,那么肯定是新朋友啦,否则是老朋友。

sql="SELECT * FROM tab where id=-1"
set rs=server.createobject("ADODB.Recordset")
rs.Open sql,conn, 1, 3
rs.addnew '如果是新访客的话,在库中新增一条记录。
rs("cs")=1 '记下访问次数为1
rs("ip")=request.servervariables("remote_addr") '记下IP,
rs("dat")=now '记下当前的日期时间,
rs("dat1")=date '记下当前的日期,以后用来做第一次访问的日期,
response.cookies("keren")=rs("id") '写入一个cookies,内容就和ID一样。
response.cookies("keren").expires=date+365 '设置cookies的有效日期从现在开始,365天,

else '以上是新朋友的处理办法,对老朋友怎么办呢?看下面的:
sql="SELECT * FROM tab where id="&keren '到库中去找出我们老朋友的记录
set rs=server.createobject("ADODB.Recordset")
rs.Open sql,conn, 1, 3
rs("cs")=rs("cs")+1 '好啦,找到啦,把访问次数加上1
rs("ip")=request.servervariables("remote_addr") '看看他的IP是多少了,记下来。
rs("dat")=now '记下现在的时间,也就是最后一次访问的时间,
response.cookies("keren")=rs("id") '再把cookies写进去,我不知这句是否多余,没有试。
response.cookies("keren").expires=date+365 '设置cookies过期时间,免得一年到了我就不认得他了。

end if
rs.update '该记的都记下了,更新库吧。
rs.close '关闭recordset对象。
set conn=nothing '释放conn,我还是认为connection要随开随关才对,放到SESSION中我认为最不可取。4 %〉

好啦,记录就做好啦,有二十几行代码,很简单的一个小程序,但我想,高手肯定还有高招,有高招的朋友不忘了教教阿余,
程序写好了,怎么放到页面中呢?很简单,在首页上随便找个地方,加上这行代码:〈img src="contpage.asp" width="0" height="0"〉就行了。
    接下来就是把记录显示出来,这个能做得比阿余好的人多的是,不过还是来现个丑。
文件名:dispcont.asp , 请看代码:
〈%
Set Conn=Server.CreateObject("ADODB.Connection")
Connstr="DBQ="+server.mappath("cont.asp")+";DefaultDir=;DRIVER={Microsoft Access Driver (*.mdb)};"
Conn.Open connstr '*****以上语句用于连接库,cont.asp是库文件名。

page3=request("pag")
if page3="" then page3=session("contpag") '分页数,当前分页
if page3="" then page3="1"

pa=request("pa")
if pa="" then pa=session("contpa") '每页显示数
if pa="" then pa=15 '默认每页显示15条,可任意改
session("contpag")=page3
session("contpa")=pa
pages=pa '每页显示数量***************以上一段程序用于实现分页功能

SQL="SELECT * FROM tab order by -dat,-id"
dim rs
Set rs=Server.CreateObject("ADODB.RecordSet")
rs.Open sql,conn,1,1
csi=0
cs1=0
cs100=0
csdat1=0
do while not rs.eof
csi=csi+rs("cs")
if rs("cs")=1 then cs1=cs1+1
if rs("cs")〉=100 then cs100+1
if datevalue(rs("dat"))=date then
csdat1=csdat1+1
end if
rs.movenext
loop
ZS=RS.RECORDCOUNT
'*****************************************************8以下一段程序用于分页显示
%〉


〈head〉
〈title〉卓越电脑统计〈/title〉
〈/head〉
〈body style="font-size: 9pt" bgcolor="#D8EDF8"〉
共有〈%Response.Write zs%〉条记录,现在是第〈%Response.Write page3%〉页 每页显示:[〈a href="dispcont.asp?pag=〈%=page3%〉&pa=15"〉15]条、[〈a href="dispcont.asp?pag=〈%=page3%〉&pa=20"〉20]条、[〈a href="dispcont.asp?pag=〈%=page3%〉&pa=30"〉30]条、[〈a href="dispcont.asp?pag=〈%=page3%〉&pa=40"〉40]条
[〈a href="dispcont.asp"〉刷新]
〈div align="left"〉
〈table border="0" cellpadding="0" style="font-size: 9pt"〉
〈tr〉〈td〉页码〈/td〉〈%page2=1
for i=1 to zs step pages
if page3=cstr(page2) then
%〉〈td 〉[〈%Response.Write page2%〉]〈/td〉
〈% else %〉
〈td 〉〈a href="dispcont.asp?pag=〈%Response.Write page2%〉"〉[〈%Response.Write page2%〉]〈/td〉
〈% end if
page2=page2+1
next
sn=pages*(page3-1) '当前记录号=每页显示数*页数-每页显示数
if sn〉zs then sn=0
rs.move sn,1
'**********************************以上一段用于分页
%〉 〈/tr〉〈/table〉
〈/div〉 〈table style="font-size: 9pt" width="100%" bordercolorlight="#000000" border="1" bordercolordark="#FFFFFF" bgcolor="#A4D1E8" cellspacing="0" cellpadding="3"〉
〈tr〉〈td〉编号〈/td〉〈td〉最后访问首页〈/td〉〈td〉最后访问IP〈/td〉〈td〉首页次数〈/td〉〈td〉首次访问日期〈/td〉〈/tr〉〈%
for i=1 to pages
Response.Write "〈/tr〉"
Response.Write "〈td〉"&rs("ID")&"〈/td〉"
Response.Write "〈td〉"&rs("dat")&"〈/td〉"
Response.Write "〈td〉"&rs("IP")&"〈/td〉"
Response.Write "〈td〉"&rs("CS")&"〈/td〉"
Response.Write "〈td〉"&rs("DAT1")&" 〈/td〉"
Response.Write "〈/tr〉"
rs.movenext
if rs.eof then exit for
next
rs.close
%〉
〈tr〉〈td〉合计〈%=zs%〉〈/td〉〈td〉访问次数为100次以上的有〈%=cs100%〉 〈/td〉〈td〉访问次数为1的有:〈%=cs1%〉〈/td〉〈td〉总访问次数〈%=csi%〉〈/td〉〈td〉今天访问量:〈%=csdat1%〉〈/td〉〈/tr〉
〈/table〉

'****************************以上是完整的分页显示全部复制下来就可用。没有考虑一条记录也没有的情况。
您可以稍加改动,加入更多功能,好啦,最后请大家关注阿余的网站: http://www.zydn.net
这里有这个小程序的演示

第五课.通过表单创建word的一个例子

先创建一个表单,随便存一个名字好了。
xxx.html
〈form action="word_create.asp"〉
Name: 〈input type="text" name="Name" size="50" maxlength="100"〉
Email: 〈input type="text" name="Email" size="50" maxlength="100"〉
Comments:
〈textarea cols="50" rows="10" name="comments"〉〈/textarea〉
〈input type="submit" value="Submit"〉
〈/form〉

处理表单的ASP程序
word_create.asp
〈% Response.ContentType = "application/msword" %〉
〈html〉
〈% strName = Request.Querystring("Name")
strEmail = Request.Querystring("Email")
strComments = Request.Querystring("Comments")
%〉
〈head〉
〈/head〉
〈body〉
〈p align="right"〉〈%=formatdatetime(now,2)%〉〈/p〉

亲爱的
〈%= strname %〉:
我的EMAIL是: 〈%= stremail %〉
我的内容是: 〈%= strComments %〉
〈/body〉
〈/html〉

第六课.用文本+ASP打造新闻发布系统

//图片上传
〈SCRIPT RUNAT=SERVER LANGUAGE=VBSCRIPT〉
Function GetUpload(FormData)
Dim DataStart,DivStr,DivLen,DataSize,FormFieldData
'分隔标志串(+CRLF)
DivStr = LeftB(FormData,InStrB(FormData,str2bin(VbCrLf)) + 1)
'分隔标志串长度
DivLen = LenB(DivStr)
PosOpenBoundary = InStrB(FormData,DivStr)
PosCloseBoundary = InStrB(PosOpenBoundary + 1,FormData,DivStr)
Set Fields = CreateObject("Scripting.Dictionary")
While PosOpenBoundary 〉 0 And PosCloseBoundary 〉 0
'name起始位置(name="xxxxx"),加6是因为[name="]长度为6
FieldNameStart = InStrB(PosOpenBoundary,FormData,str2bin("name=")) + 6
FieldNameSize = InStrB(FieldNameStart,FormData,ChrB(34)) - FieldNameStart '(")的ASC值=34
FormFieldName = bin2str(MidB(FormData,FieldNameStart,FieldNameSize))
'filename起始位置(filename="xxxxx")
FieldFileNameStart = InStrB(PosOpenBoundary,FormData,str2bin("filename=")) + 10
If FieldFileNameStart 〈 PosCloseBoundary And FieldFileNameStart 〉 PosopenBoundary Then
FieldFileNameSize = InStrB(FieldFileNameStart,FormData,ChrB(34)) - FieldFileNameStart '(")的ASC值=34
FormFileName = bin2str(MidB(FormData,FieldFileNameStart,FieldFileNameSize))
Else
FormFileName = ""
End If
'Content-Type起始位置(Content-Type: xxxxx)
FieldFileCTStart = InStrB(PosOpenBoundary,FormData,str2bin("Content-Type:")) + 14
If FieldFileCTStart 〈 PosCloseBoundary And FieldFileCTStart 〉 PosOpenBoundary Then
FieldFileCTSize = InStrB(FieldFileCTStart,FormData,str2bin(VbCrLf & VbCrLf)) - FieldFileCTStart
FormFileCT = bin2str(MidB(FormData,FieldFileCTStart,FieldFileCTSize))
Else
FormFileCT = ""
End If
'数据起始位置:2个CRLF开始
DataStart = InStrB(PosOpenBoundary,FormData,str2bin(VbCrLf & VbCrLf)) + 4
If FormFileName 〈〉 "" Then
'数据长度,减1是因为数据文件的存取字节数问题(可能是AppendChunk方法的问题):
'由于字节数为奇数的图象存到数据库时会去掉最后一个字符导致图象不能正确显示,
'字节数为偶数的数据文件就不会出现这个问题,因此必须保持字节数为偶数。
DataSize = InStrB(DataStart,FormData,DivStr) - DataStart - 1
FormFieldData = MidB(FormData,DataStart,DataSize)
Else
'数据长度,减2是因为分隔标志串前有一个CRLF
DataSize = InStrB(DataStart,FormData,DivStr) - DataStart - 2
FormFieldData = bin2str(MidB(FormData,DataStart,DataSize))
End If

'建立一个Dictionary集存储Form中各个Field的相关数据
Set Field = CreateUploadField()
Field.Name = FormFieldName
Field.FilePath = FormFileName
Field.FileName = GetFileName(FormFileName)
Field.ContentType = FormFileCT
Field.Length = LenB(FormFieldData)
Field.Value = FormFieldData
Fields.Add FormFieldName, Field
PosOpenBoundary = PosCloseBoundary
PosCloseBoundary = InStrB(PosOpenBoundary + 1,FormData,DivStr)
Wend
Set GetUpload = Fields
End Function

'把二进制字符串转换成普通字符串函数
Function bin2str(binstr)
Dim varlen,clow,ccc,skipflag
'中文字符Skip标志
skipflag=0
ccc = ""
If Not IsNull(binstr) Then
varlen=LenB(binstr)
For i=1 To varlen
If skipflag=0 Then
clow = MidB(binstr,i,1)
'判断是否中文的字符
If AscB(clow) 〉 127 Then
'AscW会把二进制的中文双字节字符高位和低位反转,所以要先把中文的高低位反转
ccc =ccc & Chr(AscW(MidB(binstr,i+1,1) & clow))
skipflag=1
Else
ccc = ccc & Chr(AscB(clow))
End If
Else
skipflag=0
End If
Next
End If
bin2str = ccc
End Function

'把普通字符串转成二进制字符串函数
Function str2bin(varstr)
str2bin=""
For i=1 To Len(varstr)
varchar=mid(varstr,i,1)
varasc = Asc(varchar)
' asc对中文字符求出来的值可能为负数,
' 加上65536就可求出它的无符号数值
' -1在机器内是用补码表示的0xffff,
' 其无符号值为65535,65535=-1+65536
' 其他负数依次类推。
If varasc〈0 Then
varasc = varasc + 65535
End If
'对中文的处理:把双字节低位和高位分开
If varasc〉255 Then
varlow = Left(Hex(Asc(varchar)),2)
varhigh = right(Hex(Asc(varchar)),2)
str2bin = str2bin & chrB("&H" & varlow) & chrB("&H" & varhigh)
Else
str2bin = str2bin & chrB(AscB(varchar))
End If
Next
End Function

'取得文件名(去掉Path)
Function GetFileName(FullPath)
If FullPath 〈〉 "" Then
FullPath = StrReverse(FullPath)
FullPath = Left(FullPath, InStr(1, FullPath, "\") - 1)
GetFileName = StrReverse(FullPath)
Else
GetFileName = ""
End If
End Function
〈/SCRIPT〉
〈SCRIPT RUNAT=SERVER LANGUAGE=JSCRIPT〉
function CreateUploadField(){ return new uf_Init() }
function uf_Init(){
this.Name = null
this.FileName = null
this.FilePath = null
this.ContentType = null
this.Value = null
this.Length = null
}
〈/SCRIPT〉

//新闻添加
〈!--#include file="news_session.asp"--〉
〈html〉
〈head〉

〈meta http-equiv="Content-Language" content="zh-cn"〉
〈meta http-equiv="Content-Type" content="text/html; charset=gb2312"〉
〈style type="text/css"〉
.buttonface {
BACKGROUND-COLOR: #0079F2; BORDER-BOTTOM: #333333 1px outset; BORDER-LEFT: #333333 1px outset; BORDER-RIGHT: #ffffff 1px outset; BORDER-TOP: #ffffff 1px outset; COLOR: #ffffff; FONT-SIZE: 9pta { color: #000000; text-decoration: none}
〈/style〉
〈SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript〉
〈!--

function client_onblur(ii) {
server=eval("form1.server"+ii)
if(server.value==""){
client=eval("form1.client"+ii)
clientvalue=client.value+""
varlen=clientvalue.length
a=clientvalue.lastIndexOf('\\')
clientvalue=clientvalue.substring(a+1)
//alert(clientvalue);
server.value=clientvalue
}
}
function form1_onsubmit() {
for(i=1;i〈1;i++){
client=eval("form1.client"+i)
server=eval("form1.server"+i)
if(client.value!="" && server.value==""){alert("上传后的文件名不能空!");server.focus();return false}
}
}

//--〉
〈/SCRIPT〉
〈title〉新闻发布系统〈/title〉
〈/head〉
〈body bgcolor=#EDF0F5 topmargin=10 marginheight=5 leftmargin=4 marginwidth=0〉

〈form method="POST" action="news_input.asp" name="form1" enctype="multipart/form-data" LANGUAGE=javascript onsubmit="return form1_onsubmit()"〉
〈div align="left"〉
〈table border="1" width="754" height="404"〉
〈tr align="center"〉
〈td width="754" height="28" colspan="3" style="font-size:11pt"〉〈strong〉新闻发布系统后台管理--新闻添加〈/strong〉〈/td〉
〈/tr〉
〈tr〉
〈td width="121" height="16" align="center" style="font-size:9pt"〉新闻标题〈/td〉
〈td width="617" height="16" colspan="2"〉
〈input type="text" name="news_title" size="87"〉〈/td〉
〈/tr〉
〈tr〉
〈td width="121" height="165" align="center" style="font-size:9pt"〉新闻内容〈/td〉
〈td width="617" height="165" colspan="2"〉〈textarea rows="11" name="news_content" cols="85"〉〈/textarea〉〈/td〉
〈/tr〉
〈tr〉
〈td width="121" height="21" align="center" style="font-size:9pt"〉新闻来源〈/td〉
〈td width="617" height="21" colspan="2"〉
〈input type="text" name="news_src" size="87"〉〈/td〉
〈/tr〉
〈tr〉
〈td width="121" height="20" align="center" style="font-size:9pt" 〉图片上传〈/td〉
〈td width="617" height="20" colspan="2"〉
〈input type="file" name="client1" size="20" readonly LANGUAGE=javascript onblur="return client_onblur(1)" 〉
〈span style="font-size:9pt"〉〈/span〉 〈INPUT type="hidden" name="server1"〉 〈input type="hidden" value="mysession" name="mysession"〉 〈/td〉
〈/tr〉
〈/table〉
〈/div〉
〈p〉
〈input type="submit" value="递交" name="B1" class="buttonface"〉 〈input type="reset" value="全部重写" name="B2" class="buttonface"〉
〈input type="button" value="帐号修改"  name="B2" style="font-size:10pt;color:#000000;" class="buttonface"〉
〈input type="button" value="新闻修改"  name="B2" style="font-size:10pt;color:#000000;" class="buttonface"〉〈/p〉
〈/form〉
〈/body〉
〈/html〉

'###################
news_input.asp
〈!--#include file="upload.inc"--〉
〈%
'Fields("xxx").Name 取得Form中xxx(Form Object)的名字
'Fields("xxx").FilePath 如果是file Object 取得文件的完整路径
'Fields("xxx").FileName 如果是file Object 取得文件名
'Fields("xxx").ContentType 如果是file Object 取得文件的类型
'Fields("xxx").Length 取得Form中xxx(Form Object)的数据长度
'Fields("xxx").Value 取得Form中xxx(Form Object)的数据内容
Dim FormData,FormSize,gnote,bnote,notes,binlen,binstr
FormSize=Request.TotalBytes
FormData=Request.BinaryRead(FormSize)
Set Fields = GetUpload(FormData)

'############判断输入错误
dim news_title,news_content,news_src,mysession

mysession=Fields("mysession").value
if len(mysession)=0 then
Response.Write "非法登陆或超时请重新登陆"
Response.End
end if

news_title=Fields("news_title").value
news_title=replace(news_title,"|","|")
news_content=Fields("news_content").value
news_src=Fields("news_src").value
news_src=replace(news_src,"|","|")
if len(news_title)=0 then%〉
〈script〉
alert("出错!新闻标题不能为空");
history.go(-1);
//window.location="news_add.asp";
〈/script〉
〈%Response.end
end if

if len(news_content)=0 then%〉
〈script〉
alert("出错!新闻内容不能为空");
history.go(-1);
〈/script〉
〈%end if

if len(news_src)=0 then%〉
〈script〉
alert("出错!新闻来源不能为空");
history.go(-1);
〈/script〉
〈%Response.end
end if

dim varchar
varchar=right(Fields("server1").value,3)
if len(varchar)〈〉0 then
if varchar〈〉"gif" and varchar〈〉"jpg" then
%〉
〈script〉
alert("出错!不能上传该图片类型");
history.go(-1);
〈/script〉
〈% Response.end
else
end if
end if
'###########将图片写入文件夹
set file_O=Server.CreateObject("Scripting.FileSystemObject")

'##########当前时间做图片名
dim newname,mytime,newfile,filename,id,image
endname=right(fields("server1").value,4)
mytime=now()
id=Year(mytime)&Month(mytime)&Day(mytime)&Hour(mytime)&Minute(MyTime)&Second(MyTime)
imageid=id&endname

'#############写入图片
newfile="client1"
filename=Fields("server1").value
If Fields(newfile).FileName〈〉"" Then
file_name=Server.MapPath("./images/"&imageid&"")
set outstream=file_O.CreateTextFile(file_name,true,false)
binstr=Fields(newfile).Value
binlen=1
varlen=lenb(binstr)
for i=1 to varlen
clow = MidB(binstr,i,1)
If AscB(clow) = 255 then
outstream.write chr(255)
binlen=binlen+1
if (i mod 2)=0 then
notes=gnote
exit for
end if
elseif AscB(clow) 〉 128 then
clow1=MidB(binstr,i+1,1)
if AscB(clow1) 〈64 or AscB(clow1) =127 or AscB(clow1) = 255 then
binlen=binlen+1
'if (binlen mod 2)=0 then
binlen=binlen+1
outstream.write Chr(AscW(ChrB(128)&clow))
'end if
notes=bnote
exit for
else
outstream.write Chr(AscW(clow1&clow))
binlen=binlen+2
i=i+1
if (i mod 2)=0 then
notes=gnote
exit for
end if
end if
else
outstream.write chr(AscB(clow))
binlen=binlen+1
if (i mod 2)=0 then
notes=gnote
exit for
end if
end if
next
outstream.close
set outstream=file_O.OpenTextFile(file_name,8,false,-1)
outstream.write midb(Fields(newfile).Value,binlen)
outstream.close
if notes=bnote then notes=notes&(binlen-1)&"字节处。"
End If

'###################################################################################### 把新闻数据结构写入newslist文件
dim mappath,mytext,myfso,contenttext,news_addtime,news_point
news_point=1
news_addtime=mytime
set myfso=createobject("scripting.filesystemobject")
mappath=server.mappath("./")
set mytext=myfso.opentextfile(mappath&"\new_list.asp",8,-1)
dim mytext2
if len(varchar)〈〉0 then
mytext2=trim(id&","&news_title&","&id&".txt"&","&news_src&","&news_point&","&news_addtime&","&imageid&"|")
else
mytext2=trim(id&","&news_title&","&id&".txt"&","&news_src&","&news_point&","&news_addtime&"|")
end if
mytext.writeline(mytext2)
mytext.close
'##############把新闻内容写入相应的文件中
set contenttext=myfso.OpenTextFile(mappath&"\news_content\"&id&".txt",8,-1)
function htmlencode2(str) '#############字符处理函数
dim result
dim l
l=len(str)
result=""
dim i
for i = 1 to l
select case mid(str,i,1)
case chr(34)
result=result+"''"
case "&"
result=result+"&"
case chr(13)
result=result+"〈br〉"
case " "
result=result+" "
case chr(9)
result=result+" "
case chr(32)
if i+1〈=l and i-1〉0 then
if mid(str,i+1,1)=chr(32) or mid(str,i+1,1)=chr(9) or mid(str,i-1,1)=chr(32) or mid(str,i-1,1)=chr(9) then
result=result+" "
else
result=result+" "
end if
else
result=result+" "
end if
case else
result=result+mid(str,i,1)
end select
next
htmlencode2=result
end function
'############################################################################

contenttext.write htmlencode2(news_content)
contenttext.close
set myfso=nothing
%〉
〈script〉
alert("发布成功");
window.location="news_add.asp";
〈/script〉

//新闻列表显示
〈%
dim myfso,myread
set myfso=createobject("scripting.filesystemobject")
set myread=myfso.opentextfile(server.mappath("./new_list.asp"),1,0)
if myread.atendofstream then
Response.Write "目前没有添加新闻"
Response.End
else
dim mytext,listarray
mytext=myread.readall
listarray=split(mytext,"|") '#######把所有记录分割成一个数组a
dim recordcount,pagecount, pagesize, pagenum
recordcount=ubound(listarray)'############记录条数
pagesize=2
pagecount=recordcount/pagesize '#######取得页面数
if instr(1,pagecount,".")=null or instr(1,pagecount,".")=0 then
pagenum=pagecount
else
pagenum=int(pagecount)+1
end if
dim topage
topage=cint(Request.QueryString ("topage")) '########取得要显示的页面
if topage〈=0 then
topage=1
end if
if topage〉pagenum then
topage=pagenum
end if
dim i,j,n
b=listarray
for i=0 to recordcount-1 '########把每一条记录组成一个数组
j=split(listarray(i),",")
if ubound(j)=6 then
b(i)="〈SPAN style='COLOR: #ffbd00; FONT-SIZE: 7px'〉〈li〉〈/SPAN〉〈span style='font-size:10pt'〉〈a href='news_view.asp?id=" & j(0) & "' target=blank〉" & j(1) & "(图)〈/a〉 点击:" & j(4)&"次 最后发布时间:"&j(5)&"〈/span〉"
else
b(i)="〈SPAN style='COLOR: #ffbd00; FONT-SIZE: 7px'〉〈li〉〈/SPAN〉〈span style='font-size:10pt'〉〈a href='news_view.asp?id=" & j(0) & "' target=blank〉" & j(1) & "〈/a〉 点击:" & j(4)&"次 最后发布时间:"&j(5)&"〈/span〉"
end if
next
'########把记录反排序存储在新的数组实现按时间反排序
dim c(100)
n=0
for i=recordcount to 0 step -1
c(n)=b(i)
n=n+1
next
dim currentrecord
currentrecord=pagesize*(topage-1)+1 '#########显示每一页
for k=1 to pagesize
if len(c(currentrecord))=0 then
exit for
end if
Response.Write c(currentrecord)&"〈br〉"
currentrecord=currentrecord+1
next
Response.Write "〈body bgcolor=#EDF0F5 topmargin=10 marginheight=5 leftmargin=4 marginwidth=0〉"
for m=1 to pagenum
response.write "〈span style=font-size:10pt〉〈a href=news_list.asp?topage="&m&"〉"&m&"〈/a〉〈/span〉 "
next
end if%>
//新闻删除
〈!--#include file="news_session.asp"--〉
〈%
dim id
id=Request.QueryString ("id")
dim myfso
set myfso=createobject("scripting.filesystemobject")
if myfso.FileExists(server.mappath("./news_content/"&id&".txt"))then
myfso.DeleteFile (server.mappath("./news_content/"&id&".txt"))'#############删除新闻内容
end if
dim mytext2,myread2
set myread2=myfso.opentextfile(server.mappath("./new_list.asp"),1,0)
if myread2.atendofstream then
Response.Write "没有新闻内容"
myread2.close
Response.End
end if
mytext2=myread2.readall
myread2.close
dim listarray,i,h,count,sf,title
listarray=split(mytext2,"|") '#########读取记录并以#分割成listarray数组
count=ubound(listarray)
for i=0 to count '###########根据ID找到该新闻实现删除功能
sf=split(listarray(i),",")
if right(sf(0),7)=right(id,7) then
dim thisid
thisid=i
'#######为6说明上传了图片,删除新闻图片和该列表记录
if ubound(sf)=6 then
myfso.deletefile(server.MapPath ("./images/"&sf(6)))
end if
exit for
end if
next
dim mytext,mappath
mappath=server.mappath("./")
set mytext=myfso.createtextfile(mappath&"\new_list.asp",-1,0)
for i=0 to thisid-1' ##########把所有数据重新写入文件
mytext.write listarray(i)&"|"
next
for i=thisid+1 to ubound(listarray)
if i=ubound(listarray) then
mytext.write listarray(i)
exit for
else
mytext.write listarray(i)&"|"
end if
next
mytext.close
%〉
〈script language="javascript"〉
alert("删除成功");
location.href =("news_admin1.asp");
〈/script〉
---------------
news_view.asp
〈% Response.Expires=0
dim myid,myfso,myread,mytext1
myid=request.querystring("id")
if len(myid)=0 then
Response.Write "没有该新闻"
Response.End
end if
set myfso=createobject("scripting.filesystemobject")
set myread=myfso.opentextfile(server.mappath("./news_content/"&myid&".txt"),1,0)
if myread.atendofstream then
Response.Write "没有新闻内容"
Response.End
else
mytext1=myread.readall '#######打开对应的新闻内容文件,并读取用变量存储
function htmlencode2(str)'###########字符处理函数
dim result
dim l
l=len(str)
result=""
dim i
for i = 1 to l
select case mid(str,i,1)
case chr(34)
result=result+""""
case "&"
result=result+"&"
case chr(13)
result=result+"〈br〉"
case " "
result=result+" "
case chr(9)
result=result+" "
case chr(32)
result=result+" "
if i+1〈=l and i-1〉0 then
if mid(str,i+1,1)=chr(32) or mid(str,i+1,1)=chr(9) or mid(str,i-1,1)=chr(32) or mid(str,i-1,1)=chr(9) then
result=result+" "
else
result=result+" "
end if
else
result=result+" "
end if
case else
result=result+mid(str,i,1)
end select
next
htmlencode2=result
end function
myread.close
end if
dim mytext2,myread2
set myread2=myfso.opentextfile(server.mappath("./new_list.asp"),1,0)
if myread2.atendofstream then
Response.Write "没有新闻内容"
Response.End
else
mytext2=myread2.readall
myread2.close
dim listarray,i,h
listarray=split(mytext2,"|") '#########读取记录并以#分割成listarray数组
dim count,sf,title,src
count=ubound(listarray)
for i=0 to count '###########根据ID找到该新闻并把文章点击次数加1
sf=split(listarray(i),",")
if right(sf(0),7)=right(myid,7) then
title=sf(1)
src=sf(3)
sf(4)=sf(4)+1
'#######为6说明上传了图片,存储为新的数组
if ubound(sf)=6 then
listarray(i)=sf(0)&","&sf(1)&","&sf(2)&","&sf(3)&","&sf(4)&","&sf(5)&","&sf(6)
dim mypic
mypic=sf(6)
else
listarray(i)=sf(0)&","&sf(1)&","&sf(2)&","&sf(3)&","&sf(4)&","&sf(5)
end if
'##################
exit for
end if
next
dim k,mytext,mappath
mappath=server.mappath("./")
set mytext=myfso.createtextfile(mappath&"\new_list.asp",-1,0)
for i=0 to ubound(listarray)' ##########把所有数据重新写入文件
if i=ubound(listarray) then
mytext.write listarray(i)
else
mytext.write listarray(i)&"|"
end if
next
Response.Write "〈body bgcolor=#EDF0F5 topmargin=10 marginheight=5 leftmargin=4 marginwidth=0〉"
Response.Write"〈div align=center style=font-size:13pt〉〈strong〉"&title&"〈/strong〉〈span〉〈/div〉〈br〉"
Response.Write "〈hr size=1〉"
if len(mypic)〈〉0 then
Response.write "〈center〉〈img src='./images/"&mypic&"'〉〈/center〉"
end if
Response.Write "〈span style=font-size:10pt〉"&htmlencode2(mytext1)&"〈/span〉"
Response.Write "〈br〉〈div align=right style='font-size:9pt'〉新闻来源:〈font color=red〉"&src&"〈/font〉〈/div〉"
%〉
〈OBJECT id=closes type="application/x-oleobject" classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11"〉
〈param name="Command" value="Close"〉
〈/object〉
〈center〉〈input type="button" value="关闭窗口" 〉〈/center〉
〈% end if%〉
//新闻修改
‘#######news_update.asp
〈!--#include file="news_session.asp"--〉
〈SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript〉
〈!--
function client_onblur(ii) {
server=eval("form1.server"+ii)
if(server.value==""){
client=eval("form1.client"+ii)
clientvalue=client.value+""
varlen=clientvalue.length
a=clientvalue.lastIndexOf('\\')
clientvalue=clientvalue.substring(a+1)
//alert(clientvalue);
server.value=clientvalue
}
}
function form1_onsubmit() {
for(i=1;i〈1;i++){
client=eval("form1.client"+i)
server=eval("form1.server"+i)
if(client.value!="" && server.value==""){alert("上传后的文件名不能空!");server.focus();return false}
}
}
//--〉
〈/SCRIPT〉
〈% dim myid
myid=Request.QueryString ("id")
if len(myid)=0 then
Response.Write "没有该新闻"
Response.End
end if
dim myfso,myread,mytext,newscontent
'#######打开对应的新闻内容文件,并读取用变量存储
set myfso=createobject("scripting.filesystemobject")
if myfso.FileExists (server.mappath("./news_content/"&myid&".txt")) then
set myread=myfso.opentextfile(server.mappath("./news_content/"&myid&".txt"),1,0)
newscontent=myread.readall
myread.close
newscontent=replace(newscontent,"〈br〉",chr(13))
newscontent=replace(newscontent," "," ")
newscontent=replace(newscontent," ",chr(32))
newscontent=replace(newscontent,"'' ",chr(34))
else
Response.Write "该新闻已被删除"
Response.End
end if
dim mytext2,myread2 '#######打开新闻列表文件
set myread2=myfso.opentextfile(server.mappath("./new_list.asp"),1,0)
if myread2.atendofstream then
Response.Write "没有新闻内容"
Response.End
end if
mytext2=myread2.readall
dim listarray
listarray=split(mytext2,"|") '#########读取记录并以#分割成listarray数组
dim count,sf,i,title,src
count=ubound(listarray)
for i=0 to count '###########根据ID找到该新闻并用变量存储给新闻的标题
sf=split(listarray(i),",")
if right(sf(0),7)=right(myid,7) then
title=sf(1)
src=sf(3)
exit for
end if
next
%〉
〈head〉
〈style〉
td {font-size:9pt}
INPUT.buttonface {
BACKGROUND-COLOR: #0079F2; BORDER-BOTTOM: #333333 1px outset; BORDER-LEFT: #333333 1px outset; BORDER-RIGHT: #ffffff 1px outset; BORDER-TOP: #ffffff 1px inset; COLOR: black; FONT-SIZE: 9pta { color: #000000; text-decoration: none}
.text {font-size:11pt}
INPUT.buttonface2 {
BACKGROUND-COLOR: #EDF0F5; COLOR: black; FONT-SIZE: 9pta { color: #000000; text-decoration: none}
a:hover { color: white; text-decoration: underline overline; background: #007EBB}
.text {font-size:11pt}
〈/style〉
〈/head〉
〈body bgcolor=#EDF0F5 topmargin=10 marginheight=5 leftmargin=4 marginwidth=0〉
〈form method="POST" action="news_updateing.asp" name="form1" enctype="multipart/form-data" onsubmit="return form1_onsubmit()"〉
〈div align="left"〉
〈table border="1" width="752" height="240" cellspacing="0" cellpadding="0"〉
〈tr〉
〈td colspan="2" height="12" align="center" width="800" style="font-size:12pt"〉〈strong〉新闻发布系统后台管理--新闻修改〈/strong〉〈/td〉
〈/tr〉
〈tr〉
〈td width="119" height="12" style="font-size:9pt"〉新闻标题〈/td〉
〈td width="675" height="12"〉
〈input type="text" name="newtitle" size="94" value="〈%=title%〉" class="buttonface2 "〉
〈/td〉
〈/tr〉
〈tr〉
〈td width="119" height="213" style="font-size:9pt"〉
新〈br〉
闻〈br〉
内〈br〉
容〈/td〉
〈td width="675" height="213"〉
〈textarea rows="14" name="newcontent" cols="93" style="BACKGROUND-COLOR: #EDF0F5"〉〈%=newscontent%〉〈/textarea〉
〈br〉
〈/td〉
〈/tr〉
〈tr〉
〈td width="119" height="4" style="font-size:9pt"〉新闻来源〈/td〉
〈td width="675" height="4"〉
〈input type=text name="newssrc" value="〈%=src%〉" size="93" class="buttonface2 "〉
〈/td〉
〈/tr〉
〈tr〉
〈td width="119" height="5" style="font-size:9pt"〉图片上传〈/td〉
〈td width="675" height="5"〉 〈input type="file" name="client1" size="20" readonly LANGUAGE=javascript onblur="return client_onblur(1)" 〉〈/td〉
〈/tr〉
〈/table〉
〈/div〉
〈p〉
〈input type="submit" value="确认" name="B1" style="font-size: 10pt; color: #000000; " class="buttonface"〉
〈input type="reset" value="全部重写" name="B2" style="font-size:10pt;color:#000000;" class="buttonface"〉
〈input type="button" value="帐号修改"  name="B2" style="font-size:10pt;color:#000000;" class="buttonface"〉
〈input type="button" value="新闻添加"  name="B2" style="font-size:10pt;color:#000000;" class="buttonface"〉〈/p〉
〈input type=hidden name="myid" value="〈%=myid%〉"〉
〈INPUT type="hidden" name="server1"〉
〈input type="hidden" name="mysession" value="mysession"〉
〈/form〉
##########
news_updating.asp
〈!--#include file="news_session.asp"--〉
〈!--#include file="upload.inc"--〉
〈%
'Fields("xxx").Name 取得Form中xxx(Form Object)的名字
'Fields("xxx").FilePath 如果是file Object 取得文件的完整路径
'Fields("xxx").FileName 如果是file Object 取得文件名
'Fields("xxx").ContentType 如果是file Object 取得文件的类型
'Fields("xxx").Length 取得Form中xxx(Form Object)的数据长度
'Fields("xxx").Value 取得Form中xxx(Form Object)的数据内容
Dim FormData,FormSize,gnote,bnote,notes,binlen,binstr
FormSize=Request.TotalBytes
FormData=Request.BinaryRead(FormSize)
Set Fields = GetUpload(FormData)
'############判断输入错误
dim mytitle,content,src,id,mysession
mysession=Fields("newtitle").value
if len(mysession)=0 then
Response.Write "非法登陆或超时间,请重新登陆"
Response.End
end if
mytitle=Fields("newtitle").value
mytitle=replace(mytitle,"|","|")
mytitle=replace(mytitle,"〈br〉","")
content=Fields("newcontent").value
src=Fields("newssrc").value
src=replace(src,"|","|")
src=replace(src,"〈br〉","")
id=trim(right(Fields("myid").value,12))
if len(mytitle)=0 then
Response.Write "〈script〉"
Response.Write "alert('出错!新闻标题不能为空!');"
Response.Write"location.href=history.go(-1);"
Response.Write "〈/script〉"
end if
if len(content)=0 then
Response.Write "〈script〉"
Response.Write "alert('出错!新闻内容不能为空!');"
Response.Write"location.href=history.go(-1);"
Response.Write "〈/script〉"
end if
if len(src)=0 then
Response.Write "〈script〉"
Response.Write "alert('出错!新闻来源不能为空!');"
Response.Write"location.href=history.go(-1);"
Response.Write "〈/script〉"
end if
'############################################################################################图片更该功能的实现
newfile="client1"
If Fields(newfile).FileName〈〉"" Then
set file_0=Server.CreateObject("Scripting.FileSystemObject")
dim contextname
contextname=right(Fields("client1").FileName,4)
imageid=id&contextname
if contextname〈〉".gif" and contextname〈〉".jpg" then '#########判断上传文件格式
Response.Write "〈script〉"
Response.Write "alert('出错!上传文件格式不对 只能为jpg/gif图片格式!');"
Response.Write"location.href=history.go(-1);"
Response.Write "〈/script〉"
end if
file_name=Server.MapPath("./images/"&imageid&"")
'#####################################如果原来有图片文件主名为id的则删除该图片
if file_0.fileexists(server.MapPath ("./images/"&id&".gif")) then
Set f3 = file_0.GetFile(server.MapPath ("./images/"&id&".gif"))
f3.Delete
end if
if file_0.fileexists(server.MapPath ("./images/"&id&".jpg")) then
Set f3 = file_0.GetFile(server.MapPath ("./images/"&id&".jpg"))
f3.Delete
end if
'########################################写入图片
set outstream=file_0.openTextFile(file_name,8,-1)
binstr=Fields("client1").Value
binlen=1
varlen=lenb(binstr)
for i=1 to varlen
clow = MidB(binstr,i,1)
If AscB(clow) = 255 then
outstream.write chr(255)
binlen=binlen+1
if (i mod 2)=0 then
notes=gnote
exit for
end if
elseif AscB(clow) 〉 128 then
clow1=MidB(binstr,i+1,1)
if AscB(clow1) 〈64 or AscB(clow1) =127 or AscB(clow1) = 255 then
binlen=binlen+1
'if (binlen mod 2)=0 then
binlen=binlen+1
outstream.write Chr(AscW(ChrB(128)&clow))
'end if
notes=bnote
exit for
else
outstream.write Chr(AscW(clow1&clow))
binlen=binlen+2
i=i+1
if (i mod 2)=0 then
notes=gnote
exit for
end if
end if
else
outstream.write chr(AscB(clow))
binlen=binlen+1
if (i mod 2)=0 then
notes=gnote
exit for
end if
end if
next
outstream.close
set outstream=file_0.OpenTextFile(file_name,8,false,-1)
outstream.write midb(Fields(newfile).Value,binlen)
outstream.close
if notes=bnote then notes=notes&(binlen-1)&"字节处。"
End If
'#######################################################################################################
dim myfso,mywrite '#######修改新闻详细内容
set myfso=createobject("scripting.filesystemobject")
if myfso.FileExists(server.mappath("./news_content/"&id&".txt")) then
myfso.DeleteFile (server.mappath("./news_content/"&id&".txt"))
end if
set mywrite=myfso.createtextfile(server.mappath("./news_content/"&id&".txt"),-1,0)
mywrite.write content
dim mytext2,myread2 '#########修改新闻的标题来源
set myread2=myfso.opentextfile(server.mappath("./new_list.asp"),1,0)
mytext2=myread2.readall
dim listarray,i,h,count,sf
listarray=split(mytext2,"|") '#########读取记录并以#分割成listarray数组
count=ubound(listarray)
for i=0 to count '###########根据ID找到该新闻记录
sf=split(listarray(i),",")
if right(sf(0),7)=right(id,7) then
sf(1)=mytitle
sf(3)=src
'#######为6说明上传了图片,存储新的数组实现查看记录点击次数加1
if ubound(sf)=6 then
If Fields(newfile).FileName〈〉"" Then
sf(6)=imageid
end if
listarray(i)=sf(0)&","&sf(1)&","&sf(2)&","&sf(3)&","&sf(4)&","&sf(5)&","&sf(6)
else
listarray(i)=sf(0)&","&sf(1)&","&sf(2)&","&sf(3)&","&sf(4)&","&sf(5)
end if
'##################
exit for
end if
next
function htmlencode2(str) '#############字符处理函数
dim result
dim l
l=len(str)
result=""
dim i
for i = 1 to l
select case mid(str,i,1)
case chr(34)
result=result+"''"
case "&"
result=result+"&"
case chr(13)
result=result+"〈br〉"
case " "
result=result+" "
case chr(9)
result=result+" "
case chr(32)
if i+1〈=l and i-1〉0 then
if mid(str,i+1,1)=chr(32) or mid(str,i+1,1)=chr(9) or mid(str,i-1,1)=chr(32) or mid(str,i-1,1)=chr(9) then
result=result+" "
else
result=result+" "
end if
else
result=result+" "
end if
case else
result=result+mid(str,i,1)
end select
next
htmlencode2=result
end function
'##########################
dim k,mytext,mappath
mappath=server.mappath("./")
set mytext=myfso.createtextfile(mappath&"\new_list.asp",-1,0)
for i=0 to ubound(listarray)' ##########把所有数据重新写入文件
if i=ubound(listarray) then
mytext.write htmlencode2(listarray(i))
else
mytext.write htmlencode2(listarray(i)&"|")
end if
next
%〉
〈script language="javascript"〉
alert("更改成功");
window.location=("news_admin1.asp");
〈/script〉



第七课.用ASP实现对MP3曲目信息的操作

先简单说一下MP3的ID3 标记,因为主要是操作这个玩意
MP3最开始的时候没有我们今天看到的那样,有歌手、年代,专集等等信息
只有一些简单的参数如yes/no来表示是不是privated或者copyrighted等信息,这样对MP3的相关工作带来了很多不便,1996年的时候有个老外提出来在每个MP3后面追加一段数据,用以存放上述的那些信息,后来就发展成为id3 v1 据我所知的现在已经到1.1了,具体的还是自己去查一下吧
还是老习惯,用metadata来引入DLL,我以前有文章贴过的,不知道的请自己去查
看代码
〈!--METADATA TYPE="typelib"
UUID="00000205-0000-0010-8000-00AA006D2EA4"
NAME="ADODB Type Library"
--〉
〈%
Function ConvertBin(Binary)
'This function converts a binary byte into an ASCII byte.
for i = 1 to LenB(Binary)
strChar = chr(AscB(MidB(Binary,i,1)))
ConvertBin = ConvertBin & strChar
Next
End Function
dim objStream
dim strTag, strSongName, strArtist, strAlbum, strYear, _
strComment, strGenre, strFile
'Specify the folder to iterate through, displaying all the MP3s
Const folder = "C:\mp3s\"
'Grab the folder information
Dim objFSO, objFolder, objFile
Set objFSO = Server.CreateObject("Scripting.FileSYstemObject")
Set objFolder = objFSO.GetFolder(folder)
'Create the Stream object
set objStream = Server.CreateObject("ADODB.Stream")
objStream.Type = adTypeBinary
'Loop through the files in the folder
For Each objFile in objFolder.Files
'Open the stream
objStream.Open
objStream.LoadFromFile objFile.Path
'Read the last 128 bytes
objStream.Position = objStream.size - 128
'Read the ID3 v1 tag info
strTag = ConvertBin(objStream.Read(3))
if ucase(strTag) = "TAG" then
strSongName = ConvertBin(objStream.Read(30))
strArtist = ConvertBin(objStream.Read(30))
strAlbum = ConvertBin(objStream.Read(30))
strYear = ConvertBin(objStream.Read(4))
strComment = ConvertBin(objStream.Read(30))
end if
'Display the results
response.write "〈table〉〈tr〉〈td colspan=2〉〈h3〉" & _
"ID3 Tag info for:〈/td〉〈/tr〉〈tr〉" & _
"〈td colspan=2〉" & objFile.Name & "〈/td〉〈/tr〉"
response.write "〈tr〉〈td〉〈b〉Artist: 〈/b〉〈/td〉" & _
"〈td〉" & strArtist & "〈/td〉〈/tr〉"
response.write "〈tr〉〈td〉〈b〉Track: 〈/b〉〈/td〉" & _
"〈td〉" & strSongName & "〈/td〉〈/tr〉"
response.write "〈tr〉〈td〉〈b〉Album: 〈/b〉〈/td〉" & _
〈td〉" & strAlbum & "〈/td〉〈/tr〉"
response.write "〈tr〉〈td〉〈b〉Year: 〈/b〉〈/td〉" & _
"〈td〉" & strYear & "〈/td〉〈/tr〉"
response.write "〈tr〉〈td〉〈b〉Comment: 〈/b〉" & _
"〈/td〉〈td〉" & strComment & "〈/td〉〈/tr〉"
response.write "〈/table〉"
objStream.Close
Response.Write "〈p〉〈hr〉〈p〉"
Next
Set objStream = Nothing 'Clean up...
%〉

自己试试吧
希望能对你有所帮助

第八课.ASP设计常见问题及解答精要

作为微软推出的网页与数据库解决方案,ASP由于有微软得天独厚的操作系统等技术后盾支持,因此得到了迅速的发展,并且正受到越来越多的欢迎,在目前在电子商务网站的建设中有很多都使用ASP来编写程序。

近来有很多的读者向我们咨询学习ASP的方法和在学习中遇到的一些问题,其中有一些是初学者经常遇到和面临的问题。为了让读者在学习ASP的过程中加深对ASP的了解,并能够有效地解决遇到的问题,我们特别收集了比较有代表性的一些问题,在此列举出来并一一给予解答,希望能在这有限的篇幅里为你学习ASP助一臂之力。

1、问题:ASP是一种编程语言吗?

答:ASP不是编程语言,而是一种开发环境。ASP提供了一个在服务器端执行指令的环境,它利用了特殊的符号()来区分HTML与必须经过服务器翻译才能送往客户端的命令。它可以执行的指令包括HTML语言,Microsoft VBScript和Microsoft Jscript等,因此可以制作出功能强大的Web应用程序。

2、问题:在Web服务器上容纳多个Web站点,能使用PWS吗?

答:在PWS上只能容纳一个Web站点。为了在相同的计算机上容纳多个Web站点,需要使用Windows NT Server或Windows 2000 Server/Professional和IIS。

3、问题:如何使用6个内置ASP对象?

答:ASP提供了多个内嵌对象,无须建立就可以在指令中直接访问和使用它们,这六个对象主要有:请求(Request)对象、响应(Response)对象、工作阶段(Session)对象、应用程序(Application)对象、服务器(Server)对象、Cookies对象,这六个对象中的服务器(Server)对象可加载其他组件,这可以扩展ASP的功能。

使用Server.CreateObject所建立的对象,它的生命周期在它建立时开始,在它所在的网页程序结束时结束。如果想要让该对象跨网页使用,则可以用Session对象来记录Server.CreateObject所建立的对象。

4、问题:为什么在使用Response.Redirect的时候出现以下错误:“标题错误,已将HTTP标题写入用户端浏览器,对任何HTTP的标题所作的修改必须在写入页内容之前”?

答:Response.Redirect可以将网页转移至另外的网页上,使用的语法结构是这样的:Response.Redirect网址,其中网址可以是相对地址或绝对地址,但在IIS4.0使用与在IIS5.0使用有所不同。

在IIS4.0转移网页须在任何数据都未输出至客户端浏览器之前进行,否则会发生错误。这里所谓的数据包括HTML的卷标,例如:< HTML>,< BODY>等,而在IIS5.0中已有所改进,在IIS5.0的默认情况下缓冲区是开启的,这样的错误不再产生。

在Response对象中有一Buffer属性,该属性可以设置网站在处理ASP之后是否马上将数据传送到客户端,但设置该属性也必须在传送任何数据给客户端之前。

为保险起见,无论采用何种ASP运行平台,在页面的开始写上< % Response.Buffer=True %>,将缓冲区设置为开启,这样的错误就不会发生了。

5、问题:缓冲输出对于网页传输有没有影响?

答:在比较大的Web页中,第一部分在浏览器中出现可能会有一些延迟,但是加载整个Web页的速度比不用缓冲要快。

6、问题:在没有表单提交时查询字符串的值是否可以使用Request.QueryString集合?

答:Request对象用于读取浏览器的数据,它除了可以读取表单字段的内容,还可以用来读取附带在网址后面的参数,无论请求字符串怎样添加到链接地址中对Request来说都没有什么不同。使用get方法提交一个表单,还是跟随一个附加查询串的链接查询字符串中所有的值,都可以使用Request.QueryString集合。

7、问题:我在ASP脚本中写了很多的注释,这会不会影响服务器处理ASP文件的速度?

答:在编写程序的过程中,作注释是良好的习惯。经国外技术人员测试,带有过多注释的ASP文件整体性能仅仅会下降0.1%,也就是说在实际应用中基本上不会感觉到服务器的性能下降的。

8、问题:需不需要在每个ASP文件的开头使用< % @LANGUAGE=VBScript % >?

答:在每个ASP文件的开头使用< % @LANGUAGE=VBScript %>代码是用来通知服务器现在使用VBScript来编写程序,但因为ASP的预设程序语言是VBScript,因此忽略这样代码也可以正常运行,但如果程序的脚本语言是JavaScrip,就需要在程序第一行指明所用的脚本语言。

9、问题:我有没有必要在每一个ASP文件中使用“Option Explicit”?

答:在实际应用中,VBScript变量的概念已经模糊了,允许直接使用变量,而不用Dim声明变量,但这并不是一个好习惯,容易造成程序错误,因为可能重复定义一个变量。我们可以在程序中使用Option Explicit语句,这样在使用一个变量的时候,必须先声明它,如果使用了没有经过声明的变量,运行时,程序就会出错。

实践证明,ASP文件中使用“Option Explicit”可以使得程序出错机会降到最少,并且会大大提升整体性能。

10、问题:运行ASP文件时有什么安全措施?

答:ASP提供了很好的代码保护机制,所有的ASP代码都在服务器端执行而只返回给客户端代码执行结果。但仍不排除恶意人士对Web服务器的刻意破坏,所以在编写ASP文件时更要注意安全问题。

虽然在ASP中引入文件以inc作为扩展名,在这里仍建议以ASP作为引文件的扩展名。当这些代码在安全机制不好的Web Server上运行时,只需在地址栏上输入引入文件的地址(inc为扩展名),就可以浏览该引入文件的内容,这是由于在Web Server上,如果没有定义好解析某类型(比如inc)的动态连接库时,该文件以源码方式显示。

另外,不要把数据库文件放在网站结构内部,这样,当恶意人士获取数据库路径后,就可以轻易获取该数据库,进而肆意更改数据库内容。比较好的做法是,为数据库建立数据源名称DSN(Date Source Name),在DSN中存储了有关连接到指定数据提供者的信息,包括:“数据库的物理位置,用于访问数据库的驱动程序的类型,访问数据库的驱动程序所需要的任何其他参数”,在进行数据库访问时可以直接访问该DSN。

11、问题:评介Web数据库管理系统时,应该考虑哪些问题?

答:在评价一个Web数据库管理系统时,必须考虑到三方面的问题:多用户问题;所建立的Web数据库应该是关系型的;数据库的安全性问题。

12、问题:ADO是什么,它是如何操作数据库的?

答:ADO的全名是ActiveX Data Object(ActiveX数据对象),是一组优化的访问数据库的专用对象集,它为ASP提供了完整的站点数据库解决方案,它作用在服务器端,提供含有数据库信息的主页内容,通过执行SQL命令,让用户在浏览器画面中输入,更新和删除站点数据库的信息。

ADO主要包括Connection,Recordset和Command三个对象, 它们的主要功能如下:

·Connection对象:负责打开或连接数据库文件;

·Recordset对象:存取数据库的内容;

·Command对象:对数据库下达行动查询指令,以及执行SQL Server的存储过程。

13、问题:使用Recordset对象和Command对象来访问数据库的区别在哪里?

答:Recordset对象会要求数据库传送所有的数据,那么数据量很大的时候就会造成网络的阻塞和数据库服务器的负荷过重,因此整体的执行效率会降低。

利用Command对象直接调用SQL语句,所执行的操作是在数据库服务器中进行的,显然会有很高的执行效率。特别是在服务器端执行创建完成的存储过程,可以降低网络流量,另外,由于事先进行了语法分析,可以提高整体的执行效率。

14、问题:是否必须为每一个Recordset对象创建一个Connection对象?

答:可以同时对不同的Recordset对象使用相同的Connection对象,以节省资源。

15、问题:什么是数据库管理系统(DBMS)?

答:数据库为了保证存储在其中的数据的安全和一致,必须有一组软件来完成相应的管理任务,这组软件就是数据库管理系统,简称DBMS,DBMS随系统的不同而不同,但是一般来说,它应该包括以下几方面的内容:

数据库描述功能:定义数据库的全局逻辑结构,局部逻辑结构和其他各种数据库对象;

数据库管理功能:包括系统配置与管理,数据存取与更新管理,数据完整性管理和数据安全性管理;

数据库的查询和操纵功能:该功能包括数据库检索和修改;

数据库维护功能:包括数据引入引出管理,数据库结构维护,数据恢复功能和性能监测。

为了提高数据库系统的开发效率,现代数据库系统除了DBMS之外,还提供了各种支持应用开发的工具。

16、问题:当前流行的WEB数据库管理系统有哪些?

答:当前流行的Web数据库管理系统有微软的SQL Server、Oracle、DB2、Sybase,小规模的企业多使用Access。

17、问题:在ASP中使用ADO的AddNew方法和直接使用“Insert into...”语句有何不同?哪种方式更好?

答:ADO的AddNew方法只是将“Insert into ”语句封装了起来,所以,当对大量数据进行操作的时候,直接使用SQL语句将会大大加快存取数据的速度,因为它减少了ADO的“翻译”时间,由于SQL语句所执行的操作是直接在数据库服务器中进行的,尤其在数据量很大的时候有显著的优势。

18、问题:为什么我在ASP中使用标准的插入记录语句 insert into books(name,email) values(“kitty”, “kitty@263.com”)会出错?

答:SQL(Structured Query Language/结构式查询语言)是IBM公司在1970年代所发展出来的数据查询语言,它现在已经成为关系型数据库查询语言的标准。SQL语句是一种以英文为基础的程序语言,可以使用它来添加,管理以及存取数据库。

在SQL语句中添加时的字符串虽然可以使用双引号,但在ASP中却需要使用单引号才能正常执行。所以应当写成insert into books(name,email) values(‘kitty’,‘kitty@263.com’)。

19、问题:什么是ActiveX 控件? 在哪里可以得到这些ActiveX控件?

答:Microsoft ActiveX控件是由软件提供商开发的可重用的软件组件。除了ASP的内嵌对象外,另外安装进来的ActiveX控件也可以在ASP中使用,这样可以节省许多宝贵的开发时间,在ASP中其实也内嵌了很多的ActiveX控件可以使用。

使用ActiveX控件,可以很快地Web应用程序、以及开发工具中加入特殊的功能。例如,使用AdRotator对象来制作广告滚动板,使用FileSystemObject对象进行文件存取,使用Marquee对象实现滚动文字。

现在,已有1000多个商用的ActiveX控件,开发ActiveX控件可以使用各种编程语言,如C,C++等,以及微软公司的 Visual Java开发环境Microsoft Visual J++。 ActiveX控件一旦被开发出来,设计和开发人员就可以把它当作预装配组件,用于开发客户程序。以此种方式使用 ActiveX控件,使用者无需知道这些组件是如何开发的,在很多情况下,甚至不需要自己编程,就可以完成网页或应用程序的设计。

目前由第三方软件开发商提供的商用控件有1000多种。微软ActiveX组件库(ActiveX Component Gallery)中存着有关信息以及相关的连接,它们指向微软及第三方开发商提供的各种 ActiveX 控件。在微软ActiveX组件库(ActiveX Component Gallery)中,可以找到开发Internet增强型ActiveX 控件的公司列表。

20、问题:为什么使用strStartPort=(Request.Form ("catmenu_0")语句取到表单中起始站点的值在数据库却找不到?

答:这是因为取到的起始站点的值可能有空格,比如原意是“杭州”,但是由于空格存在,ASP程序取到的值可能就是“杭州”,而数据库中只有“杭州”的记录,当然就找不到了,解决的方法是利用Trim 函数将字符串两头空格全部去除,相应的语句为:

strStartPort=TRIM(Request.Form("catmenu_0"))

21、问题:在ASP中当变量的生命周期结束后,有几种保留变量内容的方法?

答:任何导致网页结束的操作,比如当按下浏览器的“刷新”按钮,或者关闭了浏览器,再重新打开它,都会导致变量生命周期的结束。

如果希望在网页结束执行时,还能够保留变量的内容,以备下一次执行时使用,就可以借助Application对象来实现。比如可以利用Application对象来制作统计网站访问量的计数器。

Session对象跟Application对象一样,可以在网页结束时将变量的内容存储下来,但是与Application对象不同的是,每个联机是一个独立的Session对象,简单地说就是所有联机上网者只会共享一个Application对象,但每位联机上网者却会拥有自己的Session对象。

Application对象与Session对象可以帮我们把信息记录在服务器端,而Cookies对象则会借助浏览器提供的Cookies功能将信息记录在客户端。有一点要注意,Cookies是记录在浏览器的信息,所以数据的存取并不象存取其他ASP对象(信息存储在Server端)那么简单,就实际运行来看,只有在浏览器开始浏览Server的某一网页,而Server尚未下载任何数据给浏览器之前,浏览器才能够与Server进行Cookies数据的交换。

22、问题:对象使用完后应该怎么办?

答:当使用完对象后,首先使用Close方法来释放对象所占用的系统资源;然后设置对象值为“nothing”来释放对象占用的内存,否则会因为对象太多导致WEB服务站点运行效率降低乃至崩溃,相应语句如下:

<%

对象.close

set对象= nothing

%>

23、问题:在ASP文件中读取HTML的表单字段有几种方法?

答:Request对象除了可以用来读取附带在网址后面的参数以外,也可以读取HTML表单字段的内容,经常使用的语法结构如下:

<Form name =Formname method=“Get|Post”Action=“URL”>< Form >

其中的method可以接受Get或Post两种传输的方法,其中的Post是允许传输大量数据的方法,而Get方法会将所要传输的数据附在网址后面,然后一起送达服务器,因此传送的数据量就会受到限制,但是执行效率却比Post方法好。

使用Get或Post方法都可以将数据送至服务器,使用Request对象接收数据的相对应方法如下:

Get:Request.QueryString(“字段名称”),也可以写成Request (“字段名称”)

Post:Request.Form (“字段名称”),也可以写成Request (“字段名称”)

24、问题:如何提高使用Request集合的效率?

答:在使用Request集合时,由于包含了一系列对相关集合的搜索,这比访问一个局部变量要慢得多。因此,如果打算在页面中多次使用Request集合中的一个值,应该考虑将其存贮为一个局部变量。

25、问题:在ASP页面中既可以使用VBScript,也可以使用Jscript,混合使用脚本引擎好吗?

答:虽然在ASP页面中既可以使用VBScript,也可以使用JScript。但是在同一个页面上同时使用JScript和VBScript则是不可取的。因为服务器必须实例化并尝试缓存两个(而不是一个)脚本引擎,这在一定程度上增加了系统负担。因此,从性能上考虑,不应在同一页面中混用多种脚本引擎。

26、问题:当我们建立了一个ASP文件,并且符合语法时,通过浏览器输入以下地址,或通过资源管理器打开浏览:c:\inetpub\wwwroot\a.asp,将出现无法运行的错误,并提示权限不对或文件无法访问,为何不能正常运行ASP文件?

答:这是因为ASP文件首先要求站点是具备“执行(脚本)”属性的;然后要求按照URL格式输入地址,而不是DOS格式,我们需要在电脑上安装好并启动Web服务平台,并确保ASP文件存放在Web服务器的虚拟目录下,就可以通过HTTP的格式来浏览,在浏览器的地址栏输入:“http:// Web站点名称(或站点的IP地址)/ASP文件名称”,回车后就可以在浏览器中看到服务器执行ASP文件的结果。

27、问题:什么是ASP.NET?它与ASP有什么关系?

答:Active Server Pages(ASP,活动服务器页面)就是一个比较简单编程环境,在其中,可以混合使用HTML、脚本语言以及少量组件来创建服务器端的Internet应用程序;

ASP.NET是微软力推的功能强大的编程环境,可以使用C#等多种高级语言及脚本语言、HTML、XML、XSL等来创建基于网络的应用程序。ASP.NET将C#作为一种面向对象语言,在很多方面来看,C#将成为微软的与Java相似的语言。 C#是ASP.NET开发中一个最重要的功能,微软会将C#发展成为Java的强劲对手。这也是微软.Net框架的一个重要组成部分。我认为C#是微软在编程语言领域击败对手的主要工具。

ASP.NET在面向对象性、数据库连接、大型站点应用等方面都优于ASP程序,ASP.NET还提供更多的其他方面的新特性,例如:内置的对象缓存和页面结果缓存;内置的XML支持,可用于XML数据集的简单处理;服务器控制提供了更充分的交互式制等。

ASP.NET依然完全锁定在微软的操作系统中,要真正发挥ASP.NET潜力,你要使用C#或vb.net。这两种语言将成为ASP.NET标准的核心的脚本语言。

第九课.ASP 编程中 20 个非常有用的例子

1.如何用Asp判断你的网站的虚拟物理路径

答:使用Mappath方法
< p align="center" >< font size="4" face="Arial" >< b >
The Physical path to this virtual website is:
< /b >< /font >
< font color="#FF0000" size="6" face="Arial" >
< %= Server.MapPath("\"% >
< /font >< /p >

2.我如何知道使用者所用的浏览器?
答:使用the Request object方法

strBrowser=Request.ServerVariables("HTTP_USER_AGENT"
If Instr(strBrowser,"MSIE" < > 0 Then
Response.redirect("ForMSIEOnly.htm"
Else
Response.redirect("ForAll.htm"
End If

3.如何计算每天的平均反复访问人数

答:解决方法

< % startdate=DateDiff("d",Now,"01/01/1990"
if strdate< 0 then startdate=startdate*-1
avgvpd=Int((usercnt)/startdate) % >
显示结果

< % response.write(avgvpd) % >
that is it.this page have been viewed since November 10,1998
4.如何显示随机图象

< % dim p,ppic,dpic
ppic=12
randomize
p=Int((ppic*rnd)+1)
dpic="graphix/randompics/"&p&".gif"
% >
显示

< img src="< %=dpic% >" >
5.如何回到先前的页面

答:
< a href="< %=request.serverVariables("Http_REFERER"% >" >preivous page< /a >

或用图片如:
< img src="arrowback.gif" alt="< %=request.serverVariables("HTTP_REFERER"% >" >

6.如何确定对方的IP地址

答:
< %=Request.serverVariables("REMOTE_ADDR)% >

7.如何链结到一副图片上

答:
< % @Languages=vbs cript % >
< % response.expires=0
strimagename="graphix/errors/erroriamge.gif"
response.redirect(strimagename)
% >

8.强迫输入密码对话框

答:把这句话放载页面的开头

< % response.status="401 not Authorized"
response.end
% >
9.如何传递变量从一页到另一页

答:用 HIDDEN 类型来传递变量

< % form method="post" action="mynextpage.asp" >
< % for each item in request.form % >
< input namee="< %=item% >" type="HIDDEN"
value="< %=server.HTMLEncode(Request.form(item)) % >" >
< % next % >
< /form >

10.为何我在 asp 程序内使用 msgbox,程序出错说没有权限

答:由于 asp 是服务器运行的,如果可以在服务器显示一个对话框,那么你只好等有人按了确定之后,你的程序才能继续执行,而一般服务器不会有人守着,所以微软不得不禁止这个函数,并胡乱告诉你 ( 呵呵) 没有权限。但是ASP和客户端脚本结合倒可以显示一个对话框,as follows:

< % yourVar="测试对话框"% >
< % s cript language='javas cript' >
alert("< %=yourvar% >"
< /s cript >

11.有没有办法保护自己的源代码,不给人看到

答:可以去下载一个微软的Windows s cript Encoder,它可以对asp的脚本和客户端javas cript/vbs cript脚本进行加密。。。不过客户端加密后,只有ie5才能执行,服务器端脚本加密后,只有服务器上安装有s cript engine 5(装一个ie5就有了)才能执行。

12.怎样才能将 query string 从一个 asp 文件传送到另一个?

答:前者文件加入下句: Response.Redirect("second.asp?" & Request.ServerVariables("QUERY_STRING")

13.global.asa文件总是不起作用?

答:只有web目录设置为web application, global.asa才有效,并且一个web application的根目录下 global.asa才有效。IIS4可以使用Internet Service Manager设置application setting 怎样才能使得htm文件如同asp文件一样可以执行脚本代码?

14.怎样才能使得htm文件如同asp文件一样可以执行脚本代码?

答:Internet Sevices Manager - > 选择default web site - >右鼠键- >菜单属性-〉主目录- > 应用程序设置(Application Setting)- > 点击按钮 "配置"- > app mapping - >点击按钮"Add" - > executable browse选择 \WINNT\SYSTEM32\INETSRV\ASP.DLL EXTENSION 输入 htm method exclusions 输入PUT.DELETE 全部确定即可。但是值得注意的是这样对htm也要由asp.dll处理,效率将降低。

15.如何注册组件

答:有两种方法。

第一种方法:手工注册 DLL 这种方法从IIs 3.0一直使用到IIs 4.0和其它的Web Server。它需要你在命令行方式下来执行,进入到包含有DLL的目录,并输入:regsvr32 component_name.dll 例如 c:\temp\regsvr32 AspEmail.dll 它会把dll的特定信息注册入服务器中的注册表中。然后这个组件就可以在服务器上使用了,但是这个方法有一个缺陷。当使用这种方法注册完毕组件后,该组件必须要相应的设置NT的匿名帐号有权限执行这个dll。特别是一些组件需要读取注册表,所以,这个注册组件的方法仅仅是使用在服务器上没有MTS的情况下,要取消注册这个dll,使用:regsvr32 /u aspobject.dll example c:\temp\regsvr32 /u aneiodbc.dll

第二种方法:使用MTS(Microsoft Transaction Server) MTS是IIS 4新增特色,但是它提供了巨大的改进。MTS允许你指定只有有特权的用户才能够访问组件,大大提高了网站服务器上的安全性设置。在MTS上注册组件的步骤如下:

1) 打开IIS管理控制台。

2) 展开transaction server,右键单击"pkgs installed"然后选择"new package"。

3) 单击"create an empty package"。

4) 给该包命名。

5) 指定administrator帐号或则使用"interactive"(如果服务器经常是使用administrator 登陆的话)。

6) 现在使用右键单击你刚建立的那个包下面展开后的"components"。选择 "new then component"。

7) 选择 "install new component" 。

8) 找到你的.dll文件然后选择next到完成。

要删除这个对象,只要选择它的图标,然后选择delete。

附注:特别要注意第二种方法,它是用来调试自己编写组件的最好方法,而不必每次都需要重新启动机器了。

16. ASP与Access数据库连接:

<%@ language=VBs cript%>
<%
dim conn,mdbfile
mdbfile=server.mappath("数据库名称.mdb"
set conn=server.createobject("adodb.connection"
conn.open "driver={microsoft access driver (*.mdb)};uid=admin;pwd=数据库密码;dbq="&mdbfile
%>

17. ASP与SQL数据库连接:

<%@ language=VBs cript%>
<%
dim conn
set conn=server.createobject("ADODB.connection"
con.open "PROVIDER=SQLOLEDB;DATA SOURCE=SQL服务器名称或IP地址;UID=sa;PWD=数据库密码;DATABASE=数据库名称
%>

建立记录集对象:

set rs=server.createobject("adodb.recordset"
rs.open SQL语句,conn,3,2

18. SQL常用命令使用方法:

(1) 数据记录筛选:

sql="select * from 数据表 where 字段名=字段值 order by 字段名 [desc]"
sql="select * from 数据表 where 字段名 like '%字段值%' order by 字段名 [desc]"
sql="select top 10 * from 数据表 where 字段名 order by 字段名 [desc]"
sql="select * from 数据表 where 字段名 in ('值1','值2','值3')"
sql="select * from 数据表 where 字段名 between 值1 and 值2"

(2) 更新数据记录:

sql="update 数据表 set 字段名=字段值 where 条件表达式"
sql="update 数据表 set 字段1=值1,字段2=值2 …… 字段n=值n where 条件表达式"

(3) 删除数据记录:

sql="delete from 数据表 where 条件表达式"
sql="delete from 数据表" (将数据表所有记录删除)

(4) 添加数据记录:

sql="insert into 数据表 (字段1,字段2,字段3 …) valuess (值1,值2,值3 …)"
sql="insert into 目标数据表 select * from 源数据表" (把源数据表的记录添加到目标数据表)

(5) 数据记录统计函数:

AVG(字段名) 得出一个表格栏平均值

COUNT(*|字段名) 对数据行数的统计或对某一栏有值的数据行数统计

MAX(字段名) 取得一个表格栏最大的值

MIN(字段名) 取得一个表格栏最小的值

SUM(字段名) 把数据栏的值相加

引用以上函数的方法:

sql="select sum(字段名) as 别名 from 数据表 where 条件表达式"
set rs=conn.excute(sql)

用 rs("别名" 获取统的计值,其它函数运用同上。

(5) 数据表的建立和删除:

CREATE TABLE 数据表名称(字段1 类型1(长度),字段2 类型2(长度) …… )
例:CREATE TABLE tab01(name varchar(50),datetime default now())
DROP TABLE 数据表名称 (永久性删除一个数据表)

19. 记录集对象的方法:

rs.movenext 将记录指针从当前的位置向下移一行

rs.moveprevious 将记录指针从当前的位置向上移一行

rs.movefirst 将记录指针移到数据表第一行

rs.movelast 将记录指针移到数据表最后一行

rs.absoluteposition=N 将记录指针移到数据表第N行

rs.absolutepage=N 将记录指针移到第N页的第一行

rs.pagesize=N 设置每页为N条记录

rs.pagecount 根据 pagesize 的设置返回总页数

rs.recordcount 返回记录总数

rs.bof 返回记录指针是否超出数据表首端,true表示是,false为否

rs.eof 返回记录指针是否超出数据表末端,true表示是,false为否

rs.delete 删除当前记录,但记录指针不会向下移动

rs.addnew 添加记录到数据表末端

rs.update 更新数据表记录

---------------------------------------

20. Recordset对象方法

Open方法

recordset.Open Source,ActiveConnection,CursorType,LockType,Options

Source

Recordset对象可以通过Source属性来连接Command对象。Source参数可以是一个Command对象名称、一段SQL命令、一个指定的数据表名称或是一个Stored Procedure。假如省略这个参数,系统则采用Recordset对象的Source属性。

ActiveConnection

Recordset对象可以通过ActiveConnection属性来连接Connection对象。这里的ActiveConnection可以是一个Connection对象或是一串包含数据库连接信息(ConnectionString)的字符串参数。

CursorType

Recordset对象Open方法的CursorType参数表示将以什么样的游标类型启动数据,包括adOpenForwardOnly、adOpenKeyset、adOpenDynamic及adOpenStatic,分述如下:

--------------------------------------------------------------

常数 常数值 说明

-------------------------------------------------------------

adOpenForwardOnly 0 缺省值,启动一个只能向前移动的游标(Forward Only)。

adOpenKeyset 1 启动一个Keyset类型的游标。

adOpenDynamic 2 启动一个Dynamic类型的游标。

adOpenStatic 3 启动一个Static类型的游标。

-------------------------------------------------------------

以上几个游标类型将直接影响到Recordset对象所有的属性和方法,以下列表说明他们之间的区别。

-------------------------------------------------------------

Recordset属性 adOpenForwardOnly adOpenKeyset adOpenDynamic adOpenStatic

-------------------------------------------------------------

AbsolutePage 不支持 不支持 可读写 可读写

AbsolutePosition 不支持 不支持 可读写 可读写

ActiveConnection 可读写 可读写 可读写 可读写

BOF 只读 只读 只读 只读

Bookmark 不支持 不支持 可读写 可读写

CacheSize 可读写 可读写 可读写 可读写

CursorLocation 可读写 可读写 可读写 可读写

CursorType 可读写 可读写 可读写 可读写

EditMode 只读 只读 只读 只读

EOF 只读 只读 只读 只读

Filter 可读写 可读写 可读写 可读写

LockType 可读写 可读写 可读写 可读写

MarshalOptions 可读写 可读写 可读写 可读写

MaxRecords 可读写 可读写 可读写 可读写

PageCount 不支持 不支持 只读 只读

PageSize 可读写 可读写 可读写 可读写

RecordCount 不支持 不支持 只读 只读

Source 可读写 可读写 可读写 可读写

State 只读 只读 只读 只读

Status 只读 只读 只读 只读

AddNew 支持 支持 支持 支持

CancelBatch 支持 支持 支持 支持

CancelUpdate 支持 支持 支持 支持

Clone 不支持 不支持

Close 支持 支持 支持 支持

Delete 支持 支持 支持 支持

GetRows 支持 支持 支持 支持

Move 不支持 支持 支持 支持

MoveFirst 支持 支持 支持 支持

MoveLast 不支持 支持 支持 支持

MoveNext 支持 支持 支持 支持

MovePrevious 不支持 支持 支持 支持

NextRecordset 支持 支持 支持 支持

Open 支持 支持 支持 支持

Requery 支持 支持 支持 支持

Resync 不支持 不支持 支持 支持

Supports 支持 支持 支持 支持

Update 支持 支持 支持 支持

UpdateBatch 支持 支持 支持 支持

--------------------------------------------------------------

其中NextRecordset方法并不适用于Microsoft Access数据库。

LockType

Recordset对象Open方法的LockType参数表示要采用的Lock类型,如果忽略这个参数,那么系统会以Recordset对象的LockType属性为预设值。LockType参数包含adLockReadOnly、adLockPrssimistic、adLockOptimistic及adLockBatchOptimistic等,分述如下:

-------------------------------------------------------------

常数 常数值 说明

--------------------------------------------------------------

adLockReadOnly 1 缺省值,Recordset对象以只读方式启动,无法运行AddNew、Update及Delete等方法

adLockPrssimistic 2 当数据源正在更新时,系统会暂时锁住其他用户的动作,以保持数据一致性。

adLockOptimistic 3 当数据源正在更新时,系统并不会锁住其他用户的动作,其他用户可以对数据进行增、删、改的操作。

adLockBatchOptimistic 4 当数据源正在更新时,其他用户必须将CursorLocation属性改为adUdeClientBatch才能对数据进行增、

删、改的操作。
 
posted on 2007-03-16 21:06 求勿求 阅读(1417) 评论(1)  编辑 收藏 引用 所属分类: IT歧途

FeedBack:
# re: asp编程实例
2007-03-17 20:29 | CoffeeCat
支持你
好长的文章呀,慢慢看着  回复  更多评论
  
只有注册用户登录后才能发表评论。