经典ASP代码大集合

 

1. οncοntextmenu="window.event.returnvalue=false" 将彻底屏蔽鼠标右键
<table border οncοntextmenu=return(false)><td>no</table> 可用于Table
2. <body onselectstart="return false"> 取消选取、防止复制

3. οnpaste="return false" 不准粘贴

4. οncοpy="return false;" oncut="return false;" 防止复制

5. <link rel="Shortcut Icon" href="favicon.ico"> IE地址栏前换成自己的图标

6. <link rel="Bookmark" href="favicon.ico"> 可以在收藏夹中显示出你的图标

7. <input style="ime-mode:disabled"> 关闭输入法

8. 永远都会带着框架
<script language="javascript"><!--
if (window == top)top.location.href = "frames.htm"; //frames.htm为框架网页
// --></script>

9. 防止被人frame
<SCRIPT LANGUAGE=javascript><!--
if (top.location != self.location)top.location=self.location;
// --></SCRIPT>

10. <noscript><iframe src=*.html></iframe></noscript> 网页将不能被另存为

11. <input type=button value=查看网页源代码
οnclick="window.location = 'view-source:'+ 'http://www.csdn.net/'">

12. 怎样通过asp的手段来检查来访者是否用了代理
<% if Request.ServerVariables("HTTP_X_FORWARDED_FOR")<>"" then
response.write "<font color=#FF0000>您通过了代理服务器,"& _
"真实的IP为"&Request.ServerVariables("HTTP_X_FORWARDED_FOR")
end if
%>

13. 取得控件的绝对位置

//javascript
<script language="javascript">
function getIE(e){
var t=e.offsetTop;
var l=e.offsetLeft;
while(e=e.offsetParent){
t+=e.offsetTop;
l+=e.offsetLeft;
}
alert("top="+t+"/nleft="+l);
}
</script>

//VBScript
<script language="VBScript"><!--
function getIE()
dim t,l,a,b
set a=document.all.img1
t=document.all.img1.offsetTop
l=document.all.img1.offsetLeft
while a.tagName<>"BODY"
set a = a.offsetParent
t=t+a.offsetTop
l=l+a.offsetLeft
wend
msgbox "top="&t&chr(13)&"left="&l,64,"得到控件的位置"
end function
--></script>

14. 光标是停在文本框文字的最后
<script language="javascript">
function cc()
{
var e = event.srcElement;
var r =e.createTextRange();
r.moveStart('character',e.value.length);
r.collapse(true);
r.select();
}
</script>
<input type=text name=text1 value="123" οnfοcus="cc()">

15. 判断上一页的来源
asp:
request.servervariables("HTTP_REFERER")

javascript:
document.referrer

16. 最小化、最大化、关闭窗口
<object id=hh1 classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11">
<param name="Command" value="Minimize"></object>
<object id=hh2 classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11">
<param name="Command" value="Maximize"></object>
<OBJECT id=hh3 classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11">
<PARAM NAME="Command" value="Close"></OBJECT>

<input type=button value=最小化 οnclick=hh1.Click()>
<input type=button value=最大化 οnclick=hh2.Click()>
<input type=button value=关闭 οnclick=hh3.Click()>
本例适用于IE

17.
<%
'定义数据库连接的一些常量
Const adOpenForwardOnly = 0 '游标只向前浏览记录,不支持分页、Recordset、BookMark
Const adOpenKeyset = 1 '键集游标,其他用户对记录说做的修改将反映到记录集中,但其他用户增加或删除记录不会反映到记录集中。支持分页、Recordset、BookMark
Const adOpenDynamic = 2 '动态游标功能最强,但耗资源也最多。用户对记录说做的修改,增加或删除记录都将反映到记录集中。支持全功能浏览(ACCESS不支持)。
Const adOpenStatic = 3 '静态游标,只是数据的一个快照,用户对记录说做的修改,增加或删除记录都不会反映到记录集中。支持向前或向后移动

Const adLockReadOnly = 1 '锁定类型,默认的,只读,不能作任何修改
Const adLockPessimistic = 2 '当编辑时立即锁定记录,最安全的方式
Const adLockOptimistic = 3 '只有在调用Update方法时才锁定记录集,而在此前的其他操作仍可对当前记录进行更改、插入和删除等
Const adLockBatchOptimistic = 4 '当编辑时记录不会被锁定,而更改、插入和删除是在批处理方式下完成的

Const adCmdText = &H0001
Const adCmdTable = &H0002
%>

18. 网页不会被缓存
HTM网页
<META HTTP-EQUIV="pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate">
<META HTTP-EQUIV="expires" CONTENT="Wed, 26 Feb 1997 08:21:57 GMT">
或者<META HTTP-EQUIV="expires" CONTENT="0">
ASP网页
Response.Expires = -1
Response.ExpiresAbsolute = Now() - 1
Response.cachecontrol = "no-cache"
PHP网页
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

19. 检查一段字符串是否全由数字组成
<script language="javascript"><!--
function checkNum(str){return str.match(//D/)==null}
alert(checkNum("1232142141"))
alert(checkNum("123214214a1"))
// --></script>

20. 获得一个窗口的大小
document.body.clientWidth,document.body.clientHeight

21. 怎么判断是否是字符
if (/[^/x00-/xff]/g.test(s)) alert("含有汉字");
else alert("全是字符");

22.TEXTAREA自适应文字行数的多少
<textarea rows=1 name=s1 cols=27 onpropertychange="this.style.posHeight=this.scrollHeight">
</textarea>

23. 日期减去天数等于第二个日期
<script language=javascript>
function cc(dd,dadd)
{
//可以加上错误处理
var a = new Date(dd)
a = a.valueOf()
a = a - dadd * 24 * 60 * 60 * 1000
a = new Date(a)
alert(a.getFullYear() + "年" + (a.getMonth() + 1) + "月" + a.getDate() + "日")
}
cc("12/23/2002",2)
</script>

24. 选择了哪一个Radio
<HTML><script language="vbscript">
function checkme()
for each ob in radio1
if ob.checked then window.alert ob.value
next
end function
</script><BODY>
<INPUT name="radio1" type="radio" value="style" checked>Style
<INPUT name="radio1" type="radio" value="barcode">Barcode
<INPUT type="button" value="check" οnclick="checkme()">
</BODY></HTML>

25.获得本页url的request.servervariables("")集合
Response.Write "<TABLE border=1><!-- Table Header --><TR><TD><B>Variables</B></TD><TD><B>value</B></TD></TR>"
for each ob in Request.ServerVariables
Response.Write "<TR><TD>"&ob&"</TD><TD>"&Request.ServerVariables(ob)&"</TD></TR>"
next
Response.Write "</TABLE>"

26.
本机ip<%=request.servervariables("remote_addr")%>
服务器名<%=Request.ServerVariables("SERVER_NAME")%>
服务器IP<%=Request.ServerVariables("LOCAL_ADDR")%>
服务器端口<%=Request.ServerVariables("SERVER_PORT")%>
服务器时间<%=now%>
IIS版本<%=Request.ServerVariables"SERVER_SOFTWARE")%>
脚本超时时间<%=Server.ScriptTimeout%>
本文件路径<%=server.mappath(Request.ServerVariables("SCRIPT_NAME"))%>
服务器CPU数量<%=Request.ServerVariables("NUMBER_OF_PROCESSORS")%>
服务器解译引擎<%=ScriptEngine & "/"& ScriptEngineMajorVersion &"."&ScriptEngineMinorVersion&"."& ScriptEngineBuildVersion %>
服务器操作系统<%=Request.ServerVariables("OS")%>

27.ENTER键可以让光标移到下一个输入框
<input οnkeydοwn="if(event.keyCode==13)event.keyCode=9">

28. 检测某个网站的链接速度:
把如下代码加入<body>区域中:
<script language=javascript>
tim=1
setInterval("tim++",100)
b=1

var autourl=new Array()
autourl[1]="www.njcatv.net"
autourl[2]="javacool.3322.net"
autourl[3]="www.sina.com.cn"
autourl[4]="www.nuaa.edu.cn"
autourl[5]="www.cctv.com"

function butt(){
document.write("<form name=autof>")
for(var i=1;i<autourl.length;i++)
document.write("<input type=text name=txt"+i+" size=10 value=测试中……> =》<input type=text name=url"+i+" size=40> =》<input type=button value=GO οnclick=window.open(this.form.url"+i+".value)><br/>")
document.write("<input type=submit value=刷新></form>")
}
butt()
function auto(url){
document.forms[0]["url"+b].value=url
if(tim>200)
{document.forms[0]["txt"+b].value="链接超时"}
else
{document.forms[0]["txt"+b].value="时间"+tim/10+"秒"}
b++
}
function run(){for(var i=1;i<autourl.length;i++)document.write("<img src=http://"+autourl[i]+"/"+Math.random()+" width=1 height=1 οnerrοr=auto('http://";+autourl[i]+"')>")}
run()</script>

29. 各种样式的光标
auto :标准光标
default :标准箭头
hand :手形光标
wait :等待光标
text :I形光标
vertical-text :水平I形光标
no-drop :不可拖动光标
not-allowed :无效光标
help :?帮助光标
all-scroll :三角方向标
move :移动标
crosshair :十字标
e-resize
n-resize
nw-resize
w-resize
s-resize
se-resize
sw-resize

1.本地无缓存,每次自动刷新
response.expires=0
response.addHeader pragma , no-cache
response.addHeader cache-control , private

2.修改contentType并下载gif等格式
<%
function dl(f,n)
on error resume next

set s=CreateObject(Adodb.Stream)
S.Mode=3
S.Type=1
S.Open
s.LoadFromFile(server.mappath(f))
if err.number>0 then
  response.write err.number & : & err.description
else
  response.contentType=application/x-gzip
  response.addheader Content-Disposition:,attachment; filename= & n
  response.binarywrite(s.Read(s.size))
end if
end function

call dl(012922501.gif,t1.gif)
%>


1。忽视右键
 <body οncοntextmenu="return false">
 或
 <body style="overflow-y:hidden">
2。加入背景音乐
 IE:<bgsound src="*.mid" loop=infinite>
 NS:<embed src="*.mid" autostart=true hidden=true loop=true>
 </embed>
 *.mid你的背景音乐的midi格式文件
3。简单的window.open方法
 <a href="#"
 οnclick="javascript:window.open(文件路径/文件名,newwindow,
 toolbar=no,scrollbars=yes,resizable=no,top=0,left=0,
 width=400,height=300);">文字或图片</a>
 参数解释:
 <SCRIPT LANGUAGE="javascript"> js脚本开始;
 window.open 弹出新窗口的命令;
 文件路径/文件名 弹出窗口的文件名;
 newwindow 弹出窗口的名字(不是文件名),非必须,可用空代替;
 width=400 窗口宽度;
 height=300 窗口高度;
 top=0 窗口距离屏幕上方的象素值;
 left=0 窗口距离屏幕左侧的象素值;
 toolbar=no 是否显示工具栏,yes为显示;
 menubar,scrollbars 表示菜单栏和滚动栏。
 resizable=no 是否允许改变窗口大小,yes为允许;
 location=no 是否显示地址栏,yes为允许;
 status=no 是否显示状态栏内的信息(通常是文件已经打开),yes为允许;
 </SCRIPT> js脚本结束
4。简单的页面加密
 <script LANGUAGE="javascript">
 <!--
 function loopy(){
  var sWord ="";
  while(sWord!="login"){sWord=prompt("请输入你的登陆密码");}
  alert("登陆成功!");
 }
 loopy()
 //-->
 </script>
5。拉动页面时背景图不动
 <style>
 body{background-image:url(logo.gif);
 background-repeat:no-repeat;background-position:center}
 </style>
7。随机替换图片
 <script>
 document.write(<img src="img/+parseInt(Math.random()*(5))
 +.gif"height="40" width="50">)
 </script>
 图片文件名为0.gif 1.gif 2.gif 3.gif 4.gif
8。窗口定时关闭
 先将如下代码网页文件的区:
 <script language="javascript">
 function closeit() { setTimeout("self.close()",10000) //毫秒 }
 </script>
 然后再在<body>标内加入如:<body οnlοad="closeit()">
9。网页自动关闭
 <html>
 <head>
 <object id=closes type="application/x-oleobject"
 classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11">
 <param name="Command" value="Close">
 </object>
 </head>
 <body οnlοad="window.setTimeout(closes.Click(),10000)">
 这个窗口会在10秒过后自动关闭,而且不会出现提示.
 </body>
 </html>
10。网页自动刷新
 在head部记入
 <META HTTP-EQUIV="Refresh" content="20">
 其中20为20秒后自动刷新,你可以更改为任意值。
11。网页自动转页
 <META HTTP-EQUIV="Refresh" CONTENT="时间(秒);URL=地址">
12。保持layer在最前面,而不被Iframe、Object所覆盖
 在Layer中再插Iframe 或 Object 设z-Index值
 <div z-Index:2><object xxx></object> # 前面
 <div z-Index:1><object xxx></object> # 后面
 <div id="Layer2" style="position:absolute; top:40;width:400px;
 height:95px;z-index:2"> height=100% width=100%>
 <iframe width=0 height=0></iframe>
 </div>
 <div id="Layer1" style="position:absolute; top:50;width:200px;
 height:115px;z-index:1">
 <iframe height=100% width=100%></iframe>
 </div>
13。返回上一页
 <a href=javascript:history.back(1)>『返回上一页』</a>
14。关闭窗口
 <a href=javascript:self.close()>『关闭窗口』</a>
15。关于iframe的透明背景
 <IFRAME ID="iFrame1" SRC="iframe.htm"
 allowTransparency="true"
 style="background-color: green"></IFRAME>

分頁代碼
<table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">
 <%
sql="select  id,name,count  from [table] "
set rs=server.createobject("adodb.recordset")
rs.open sql,conn,1,1
RS.pagesize=15 '每頁記錄數
page=cint(request("page"))
if page="" or page=0 then
page=1
else
page=page
end if
rs.absolutepage=page  '取得當前頁
for i=1 to rs.pagesize
if rs.bof or rs.eof then
exit for
end if
%>
          <tr><td colspan="3" align="center"><%=rs("name")%></td></tr>  
<%
 rs.movenext
next%>
        <tr>
          <td height="23">
                    每頁15條記錄&nbsp;&nbsp;總共有 <font color="#FF0000"><%=rs.recordcount%></font>
              條記錄&nbsp;
              <%         
   If Page <= 1 Then               
      Response.Write "首頁&nbsp;  "               
      Response.Write "上一頁&nbsp;  "               
   End If            
   If Page > 1 Then               
      Response.Write "<A HREF=index.asp?Page=1>首頁</A> "               
      Response.Write "<A HREF=index.asp?Page=" & (Page-1) & ">上一頁</A> "               
   End If      
   If Page < RS.PageCount Then               
      Response.Write "<A HREF=index.asp?Page=" & (Page+1) & ">下一頁</A> "               
      Response.Write "<A HREF=index.asp?Page=" & RS.PageCount & ">末頁</A> "               
   End If
   If Page >= RS.PageCount Then               
      Response.Write "下一頁&nbsp;  "               
      Response.Write "末頁&nbsp; "               
   End If
   response.write "<font color='blue'>"              
%>       
<select name="Page" size="1" οnchange="window.location.href=this.value" class="user">
          <%For j=1 to rs.pagecount%>
          <option value="index.asp?page=<%=j%>"<%if j=Page then%>selected<%end if%>><%=j%></option>
          <%Next%>
        </select> 第<%=Page%>頁/共<%=RS.PageCount%>頁
</td>
  </tr>
</table>


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=vb-script % >
< % 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="测试对话框"% >
< % script language='java-script' >
alert("< %=yourvar% >")
< /script >

11.有没有办法保护自己的源代码,不给人看到
答:可以去下载一个微软的Windows Script Encoder,它可以对asp的脚本和客户端java-script/vb-script脚本进行加密。。。不过客户端加密后,只有ie5才能执行,服务器端脚本加密后,只有服务器上安装有script 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" [b]。
8) 找到你的.dll文件然后选择next到完成。
要删除这个对象,只要选择它的图标,然后选择delete。
附注:特别要注意第二种方法,它是用来调试自己编写组件的最好方法,而不必每次都需要重新启动机器了。

16. ASP与Access数据库连接:

<%@ language=vb-script%>
<%
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=vb-script%>
<%
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才能对数据进行增、
删、改的操作。


怎样判断检测是否checkbox的选择属性呢?
选中了会传回checkbox的value
未选中不会传回checkbox的value

checkbox全选
<head></head>
<script LANGUAGE="Javas cript">
<!-- Begin
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
for (i = 0; i < field.length; i++) {
field[i].checked = true;}
checkflag = "true";
return "false"; }
else {
for (i = 0; i < field.length; i++) {
field[i].checked = false; }
checkflag = "false";
return "true"; }
}
//  End -->
</s cript>
<body></body>
<form name="form" method="post" action="">
<input type="checkbox" name="list" value="1">
<input type="checkbox" name="list" value="2">
<input type="checkbox" name="list" value="3">
<input type=checkbox value="全选" onClick="this.value=check(this.form.list)"> 选中所有显示记录

轉貼經典實用的代碼:
     1、关闭窗口在图片的连接上写
    javascript:window.close();
  提交的图片连接写
      javascript:document.Form1.submit();
  删除之前出现确认对话框:
  <a href="del.asp?id=<%=rs("rowid")%>" ONCLICK="javascript:return confirm('真的要删除数据吗?')">删除</a>

  2、用JScript弹出提示框然后跳转到指定页面
  <%
  Response.Write "<script language='javascript'>alert(""提交成功!"");location.href=""AddBook.asp"";</script>"
  %>

  3、页面摘入等待。。。。脚本说明:
  把如下代码加入<head>区域中
  <SCRIPT LANGUAGE="JavaScript">
  document.write("<font size=6 color=blue face='楷体_GB2312'><B>正在载入首页,请稍等..</B></font>");
  window.clear;
  window.location.href="http://www.ybfq.net";
  </SCRIPT>

  4、在Text直接修改记录,然后点修改保存记录
  <%count=0
  do while not (rs.eof or rs.bof) and count<rs.PageSize %>
  <form action="webGroupEdit.asp" method="post" name="GroupEdit" onSubmit="return Checkedit()">
  <tr bgcolor="E9F3FF">
  <td>&nbsp;<%=rs("id")%> <input name="b" type="hidden" id="b" value="<%=rs("id")%>">
  <input name="currpage" type="hidden" id="currpage" value="<%=page%>"></td>
  <td height="18"><input name="a" type="text" id="a" value="<%=rs("MemGroupName")%>" size="20" maxlength="50">
  </td>
  <td height="18"><input name="c" type="text" id="c" value="<%=rs("Remark")%>" size="25" maxlength="30"></td>
  <td><input type="submit" name="Submit" value=" 修改 " ></td>
  <td><div align="center"><a href="webGroupDel.asp?id=<%=rs("id")%>&page=<%=page%>" onClick="return check()">删除</a></div></td>
  </tr>
  </form>
  <%
  count=count+1
  rs.movenext
  loop
  %>

  5、自动计算问题:
  <input type="hidden" name="selvalue">
  <Select NAME="select1" onChage="javascript:document.form1.selvalue.value=this.options[this.options.selectedIndex].text">
  <option value="1">新浪</option>
  <option value="2">百度</option>
  <option value="3">中华网</option>
  <option value="4">腾讯</option>
  </Select>


ASP初学者常犯的几个错误(轉貼)
1.记录集关闭之前再次打开:
------------------------------------
sql="select * from test"
rs.open sql,conn,1,1
if not rs.eof then
dim myName
myName=rs("name")
end if
sql="select * from myBook"
rs.open sql,conn,1,1
-------------------------------------
解决:在第二次rs.open之前先关闭 rs.close

set rs1=server.createobject
rs1.open sql,conn,1,1

2,用SQL关键字做表名或字段名
-------------------------------------
sql="select * from user"
rs.open sql,conn,1,1
-------------------------------------
user为sql关键字
解决:改为
sql="select * from [user]"


3,用锁定方式去进行update
-------------------------------------
sql="select * from [user]"
rs.open sql,conn,1,1
rs.addnew

rs("userName")="aa"
rs.update
-------------------------------------
当前记录集的打开方式为只读
解决:
改为
rs.open sql,conn,1,3

4,在查询语句中采用的对比字段值与字段类型不符
-----------------------------------------
sql="select * from [user] where id= " & myID & " "
rs.open sql,conn,1,1
-----------------------------------------
假设表中设计ID为数字型,那么些时出错。
解决:
sql="select * from [user] where id=" & myID

5,未检查变量值而出错
-----------------------------------------
sql="select * from [user] where id=" & myID
rs.open sql,conn,1,1
-----------------------------------------
假设myID变量此时值为null,那么sql将成为
sql="select * from [user] where id="
解决:
在前面加上
if isnull(myID) then 出错提示

6,未检查变量值类型而出错
-----------------------------------------
sql="select * from [user] where id=" & myID
rs.open sql,conn,1,1
-----------------------------------------
假设id为数字型,myID变量此时值不为null,但为字符,比如myID此时为"aa"
那么sql将成为
sql="select * from [user] where id=aa"
解决:
在前面加上
if isnumeric(myID)=false then 出错提示

这也可以有效防止 sql injection 漏洞攻击。

7,由于数据库文件所在目录的NTFS权限而引起的 不能更新。数据库或对象为只读"错误。
说明:
WIN2K系统延续了WINNT系统的NTFS权限。
对于系统中的文夹都有默认的安全设置。
而通过HTTP对WWW访问时的系统默认用户是 iusr_计算机名 用户 ,它属于guest组。
当通过HTTP访问时,可以ASP或JSP,也或是PHP或.NET程序对数据进行修改操作:
比如:
当打开某一个文章时,程序设定,文章的阅读次数=原阅读次数+1
执行
conn.execute("update arts set clicks=clicks+1 where id=n")
语句时,如果 iusr_计算机名 用户没有对数据库的写权限时,就会出错.
解决方法:
找到数据库所在目录
右键》属性》安全选项卡》设置 iusr_计算机名 用户的写权限(当然,也可以是everyone)


其实就是得到地址栏里"?"以后的字串
<SCRIPT language=javascript>
var srcc = window.location;
srcc = srcc.toString()
start = srcc.indexOf("?");
end = srcc.length;
</SCRIPT>


<SCRIPT LANGUAGE="javascript"> js脚本开始;
  window.open 弹出新窗口的命令;
  'page.html' 弹出窗口的文件名;
  'newwindow' 弹出窗口的名字(不是文件名),非必须,可用空''代替;
  height=100 窗口高度;
  width=400 窗口宽度;
  top=0 窗口距离屏幕上方的象素值;
  left=0 窗口距离屏幕左侧的象素值;
  toolbar=no 是否显示工具栏,yes为显示;
  menubar,scrollbars 表示菜单栏和滚动栏。
  resizable=no 是否允许改变窗口大小,yes为允许;
  location=no 是否显示地址栏,yes为允许;
  status=no 是否显示状态栏内的信息(通常是文件已经打开),yes为允许;
  </SCRIPT> js脚本结束
 
判断星期几

<%
yue=month(date())
nian=year(date())
thismon=nian&"-"&yue&"-1"
nextmon=dateadd("m",1,thismon)
tiancount=datediff("d",thismon,nextmon)  '本月的天数

wek= Weekday(date())
select case wek
case 1
response.write "周日"
case 2
response.write "周一"
case 3
response.write "周二"
case 4
response.write "周三"
case 5
response.write "周四"
case 6
response.write "周五"
case 7
response.write "周六"
end select

yue=month(date())
nian=year(date())
thismon=nian&"-"&yue&"-1"
nextmon=dateadd("m",1,thismon)
tiancount=datediff("d",thismon,nextmon)  '本月的天数
dim wek,wekday
wek= Weekday(date())
select case wek
case 1
wekday= "周日"
case 2
wekday= "周一"
case 3
wekday= "周二"
case 4
wekday= "周三"
case 5
wekday= "周四"
case 6
wekday= "周五"
case 7
wekday= "周六"
end select

'response.write "本月共"&tiancount&"天,今天是"&wekday&"
%>



<%
’判断文件名是否合法
Function isFilename(aFilename)
 Dim sErrorStr,iNameLength,i
 isFilename=TRUE
 sErrorStr=Array("/","/",":","*","?","""","<",">","|")
 iNameLength=Len(aFilename)
 If iNameLength<1 or iNameLength=null Then
  isFilename=FALSE
 Else
  For i=0 To 8
   If instr(aFilename,sErrorStr(i)) Then
    isFilename=FALSE    
   End If
  Next
 End If
End Function

’去掉字符串头尾的连续的回车和空格
function trimVBcrlf(str)
 trimVBcrlf=rtrimVBcrlf(ltrimVBcrlf(str))
end function

’去掉字符串开头的连续的回车和空格
function ltrimVBcrlf(str)
 dim pos,isBlankChar
 pos=1
 isBlankChar=true
 while isBlankChar
  if mid(str,pos,1)=" " then
   pos=pos+1
  elseif mid(str,pos,2)=VBcrlf then
   pos=pos+2
  else
   isBlankChar=false
  end if
 wend
 ltrimVBcrlf=right(str,len(str)-pos+1)
end function

’去掉字符串末尾的连续的回车和空格
function rtrimVBcrlf(str)
 dim pos,isBlankChar
 pos=len(str)
 isBlankChar=true
 while isBlankChar and pos>=2
  if mid(str,pos,1)=" " then
   pos=pos-1
  elseif mid(str,pos-1,2)=VBcrlf then
   pos=pos-2
  else
   isBlankChar=false
  end if
 wend
 rtrimVBcrlf=rtrim(left(str,pos))
end function

’判断Email是否有效,返回1表示正确
Function isEmail(aEmail)
 Dim iLocat,v,iLength,i,checkletter
 If instr(aEmail,"@") = 0 or instr(aEmail,".") = 0 Then
  isEmail=0
  EXIT FUNCTION
 End If
 iLocat=instr(aEmail,"@")
 If instr(iLocat,aEmail,".")=0 or instr(iLocat+1,aEmail,"@")>0 Then
  isEmail=0
  EXIT FUNCTION
 End If
 If left(aEmail,1)="." or right(aEmail,1)="." or left(aEmail,1)="@" or right(aEmail,1)="@" Then
  isEmail=0
  EXIT FUNCTION
 End If
 v="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-.@"
 iLength=len(aEmail)
 For i=1 To iLength
  checkletter=mid(aEmail,i,1)
  If instr(v,checkletter)=0 Then
   isEmail=0
   EXIT FUNCTION
  End If
 Next
 isEmail=1
End Function

’测试用:显示服务器信息
Sub showServer
 Dim name
 Response.write "<Table border=1 bordercolor=lightblue CELLSPACING=0>"
 for each name in request.servervariables
  Response.write "<tr>"
  Response.write "<td>"&name&"</td>"
  Response.write "<td>"&request.servervariables(name)&"<br></td>"
  Response.write "</tr>"
 next
 Response.write "</table>"
End Sub

’测试用:显示Rs结果集以及字段名称
Sub showRs(rs)
 Dim strTable,whatever
 Response.write "<center><table><tr>"
 for each whatever in rs.fields
  response.write "<td><b>" & whatever.name & "</B></TD>"
 next
 strTable = "</tr><tr><td>"&rs.GetString(,,"</td><td>","</tr><tr><td>"," ") &"</td></tr></table></center>"
 Response.Write(strTable)
End Sub

’用HTML格式显示文本
Function txt2Html(str)
 if isnull(str) then
  txt2Html=""
  exit Function
 end if
 str=Replace(str,chr(34),""")
 str=Replace(str,"<","<")
 str=Replace(str,">",">")
 str=Replace(str,chr(13)+chr(10),"<br>")
 str=Replace(str,chr(9),"    ")
 str=Replace(str," "," ")
 txt2Html=str
End Function

’测试用:显示调试错误信息
Sub showError
 Dim sErrMsg
 sErrMsg=Err.Source&" "&Err.Description
 Response.write "<center>"&sErrMsg&"</center>"
 Err.clear
End Sub

’显示文字计数器
Sub showCounter
Dim fs,outfile,filename,count
filename=server.mappath("count.txt")
Set fs = CreateObject("Scripting.FileSystemObject")
If fs.fileExists(filename) Then
 Set outfile=fs.openTextFile(filename,1)
 count=outfile.readline
 count=count+1
 Response.write "<center>浏览人次:"&count&"<center>"
 outfile.close
 Set outfile=fs.CreateTextFile(filename)
 outfile.writeline(count)
Else
 Set outfile=fs.openTextFile(filename,8,TRUE)
 count=0
 outfile.writeline(count)
END IF
outfile.close
set fs=nothing
End Sub
%>


嘿嘿,看着上面那个星期几的判断,改进一下吧。
<script>alert("今天星期"+"天一二三四五六".charAt(new Date().getDay()));</script>


其实就是得到地址栏里"?"以后的字串
<SCRIPT language=javascript>
var srcc = window.location;
srcc = srcc.toString()
start = srcc.indexOf("?");
end = srcc.length;
</SCRIPT>
-------------------------------------------------------
其实就是得到地址栏里"?"以后的字串
<script>
alert(location.search);  //这个不是比你的更为简洁了吗?
</script>
</script>

<input type=checkbox name=mm value=a οnclick="Item(this, 'mmAll')"><br>
<input type=checkbox name=mm value=b οnclick="Item(this, 'mmAll')"><br>
<input type=checkbox name=mm value=c οnclick="Item(this, 'mmAll')"><br>
<input type=checkbox name=mm value=d οnclick="Item(this, 'mmAll')"><br>
<input type=checkbox name=mm value=e οnclick="Item(this, 'mmAll')"><br><br>
<input type=checkbox name=mmAll οnclick="All(this, 'mm')">全选与不全选的切换

<script language=Javascript>
function All(e, itemName)
{
  var aa = document.getElementsByName(itemName);
  for (var i=0; i<aa.length; i++)
   aa[i].checked = e.checked; //得到那个总控的复选框的选中状态
}
function Item(e, allName)
{
  var all = document.getElementsByName(allName)[0];
  if(!e.checked) all.checked = false;
  else
  {
    var aa = document.getElementsByName(e.name);
    for (var i=0; i<aa.length; i++)
     if(!aa[i].checked) return;
    all.checked = true;
  }
}
</script>


用正则表达式限制文本类型;

只能输汉字:οnkeyup="value=value.replace(/[^/u4E00-/u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/u4E00-/u9FA5]/g,''))"

只能输入数字:οnkeyup="value=value.replace(/[^/d]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/d]/g,''))"

数字和英文:οnkeyup="value=value.replace(/[/W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/d]/g,''))"


用ASP连接各种数据库的方法
一、ASP的对象存取数据库方法
  在ASP中,用来存取数据库的对象统称ADO(Active Data Objects),主要含有三种对象:
  Connection、Recordset 、Command
  Connection:负责打开或连接数据
  Recordset:负责存取数据表
  Command:负责对数据库执行行动查询命令
  二、连接各数据库的驱动程序
  连接各数据库可以使用驱动程序,也可以使用数据源,不过我建议大家使用驱动程序,因为使用驱动程序非常
方便、简单,而使用数据源比较麻烦。
  ODBC链接
  适合数据库类型 链接方式 
access "Driver={microsoft access driver(*.mdb)};dbq=*.mdb;uid=admin;
pwd=pass;" 
dBase "Driver={microsoft dbase driver(*.dbf)};driverid=277;dbq=------------;" 
Oracle "Driver={microsoft odbc for oracle};server=oraclesever.world;uid=admin;
pwd=pass;" 
MSSQL server "Driver={sql server};server=servername;database=dbname;uid=sa;
pwd=pass;" 
MS text "Driver={microsoft text driver(*.txt; *.csv)};dbq=-----;extensions=asc,csv,tab,txt;Persist SecurityInfo=false;" 
Visual Foxpro "Driver={microsoft Visual Foxpro driver};sourcetype=DBC;sourceDB=*.dbc;
Exclusive=No;" 
MySQL "Driver={mysql};database=yourdatabase;uid=username;pwd=yourpassword;
option=16386;" 

  OLEDB链接
  适合的数据库类型 链接方式 
access "Provider=microsoft.jet.oledb.4.0;data source=your_database_path;user id=admin;
password=pass;" 
Oracle "Provider=OraOLEDB.Oracle;data source=dbname;user id=admin;password=pass;" 
MS SQL Server "Provider=SQLOLEDB;data source=machinename;initial catalog=dbname;
userid=sa;password=pass;" 
MS text "Provider=microsof.jet.oledb.4.0;data source=your_path;Extended Properties′text;
FMT=Delimited′" 

  而我们在一般情况下使用Access的数据库比较多,在这里我建议大家连接Access数据库使用下面的方法:
dim conn
set conn = server.createobject("adodb.connection")
conn.open = "provider=microsoft.jet.oledb.4.0;" & "data source = " & server.mappath
("../db/bbs.mdb") 其中../db/bbs.mdb是你的数据库存放的相对路径!如果你的数据库和ASP文件在
同一目录下,你只要这样写就可以了:
dim conn
set conn = server.createobject("adodb.connection")
conn.open = "provider=microsoft.jet.oledb.4.0;" & "data source = " & server.mappath
("bbs.mdb") 有许多初学者在遇到数据库连接时总是会出问题,然而使用上面的驱动程序只要
你的数据库路径选对了就不会出问题了


一些ASP初学者常用的代码 
1.获得系统时间:
<%=now()%>
2.取得来访用的IP:
<%=request.serverVariables("remote_host")%>
3.获得系统,浏览器版本:
<script>
window.document.write("版本:"+navigator.appName+navigator.appVersion+" browser.")
</script>
4.去除IE混动条:
<body scroll="no">
<body style="overflow-y:hidden">
5.进入网站,跳出广告:
<script language="JavaScript">
<!--
<!-- 注意更改文件所在路径-->
window.open(''http://www.XXXXXX.com'','''',''height=200,width=300,top=0,left=30'');
// -->
</script>
6.随机数:
<%randomize%>
<%=(int(rnd()*n)+1)%>
N为可改变数
7.向上混动代码:
<marquee direction="up" scrolldelay="200" style="font-size: 9pt; color: #FF0000; line-

height: 150%; font-style:italic; font-weight:bold" scrollamount="2" width="206"

height="207" bgcolor="#FFFF00">hhhhhhhhhhhhhhhhhhh</marquee>
8.自动关闭网页:
<script LANGUAGE="JavaScript">
<!--
setTimeout(''window.close();'', 10000); //60秒后关闭
// -->
</script>
<p align="center">本页10秒后自动关闭,请注意刷新页面</p>
9.随机背景音乐:
<%randomize%>
<bgsound src="mids/<%=(int(rnd()*60)+1)%>.mid" loop="-1">

可以修改数字,限制调用个数,我这里是60个.
10.自动刷新本页面:
<script>
<!--

var limit="0:10"

if (document.images){
var parselimit=limit.split(":")
parselimit=parselimit[0]*60+parselimit[1]*1
}
function beginrefresh(){
if (!document.images)
return
if (parselimit==1)
window.location.reload()
else{
parselimit-=1
curmin=Math.floor(parselimit/60)
cursec=parselimit%60
if (curmin!=0)
curtime=curmin+"分"+cursec+"秒后重刷本页!"
else
curtime=cursec+"秒后重刷本页!"
window.status=curtime
setTimeout("beginrefresh()",1000)
}
}

window.οnlοad=beginrefresh
file://-->
</script>

11.ACCESS数据库连接:
<%
option explicit
dim startime,endtime,conn,connstr,db
startime=timer()
'更改数据库名字
db="data/dvBBS5.mdb"
Set conn = Server.CreateObject("ADODB.Connection")
connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(db)
'如果你的服务器采用较老版本Access驱动,请用下面连接方法
'connstr="driver={Microsoft Access Driver (*.mdb)};dbq=" & Server.MapPath(db)
conn.Open connstr
function CloseDatabase
Conn.close
Set conn = Nothing
End Function
%>
12.SQL数据库连接:
<%
option explicit
dim startime,endtime,conn,connstr,db
startime=timer()
connstr="driver={SQL Server};server=HUDENQ-N11T33NB;uid=sa;pwd=xsfeihu;database=dvbbs"
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open connstr
function CloseDatabase
Conn.close
Set conn = Nothing
End Function
%>
13.用键盘打开网页代码:
<script language="javascript">
function ctlent(eventobject)
{
if((event.ctrlKey && window.event.keyCode==13)||(event.altKey && window.event.keyCode==83))
{
window.open('网址','','')
}
}
</script>

这里是Ctrl+Enter和Alt+S的代码 自己查下键盘的ASCII码再换就行!

14.让层不被控件复盖代码:
<div z-Index:2><object xxx></object></div> # 前面
<div z-Index:1><object xxx></object></div> # 后面
<div id="Layer2" style="position:absolute; top:40;width:400px; height:95px;z-

index:2"><table height=100% width=100% bgcolor="#ff0000"><tr><td height=100% width=100%

></td></tr></table><iframe width=0 height=0></iframe></div>
<div id="Layer1" style="position:absolute; top:50;width:200px; height:115px;z-

index:1"><iframe height=100% width=100%></iframe></div>
15.动网FLASH广告代码:
<object classid="clsid27CDB6E-AE6D-11cf-96B8-444553540000"

codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0

,0" width="468" height="60"><param name=movie value="images/yj16d.swf"><param name=quality

value=high><embed src="images/dvbanner.swf" quality=high

pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?

P1_Prod_Version=ShockwaveFlash"; type="application/x-shockwave-flash" width="468"

height="60"></embed></object>
16.VBS弹出窗口小代码:
<script language=vbscript>
msgbox"你还没有注册或登陆论坛","0","精品论坛"
location.href = "login.asp"
</script>
16.使用FSO修改文件特定内容的函数
function FSOchange(filename,Target,String)
Dim objFSO,objCountFile,FiletempData
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objCountFile = objFSO.OpenTextFile(Server.MapPath(filename),1,True)
FiletempData = objCountFile.ReadAll
objCountFile.Close
FiletempData=Replace(FiletempData,Target,String)
Set objCountFile=objFSO.CreateTextFile(Server.MapPath(filename),True)
objCountFile.Write FiletempData
objCountFile.Close
Set objCountFile=Nothing
Set objFSO = Nothing
End Function
17.使用FSO读取文件内容的函数
function FSOFileRead(filename)
Dim objFSO,objCountFile,FiletempData
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objCountFile = objFSO.OpenTextFile(Server.MapPath(filename),1,True)
FSOFileRead = objCountFile.ReadAll
objCountFile.Close
Set objCountFile=Nothing
Set objFSO = Nothing
End Function
18.使用FSO读取文件某一行的函数
function FSOlinedit(filename,lineNum)
if linenum < 1 then exit function
dim fso,f,temparray,tempcnt
set fso = server.CreateObject("scripting.filesystemobject")
if not fso.fileExists(server.mappath(filename)) then exit function
set f = fso.opentextfile(server.mappath(filename),1)
if not f.AtEndofStream then
tempcnt = f.readall
f.close
set f = nothing
temparray = split(tempcnt,chr(13)&chr(10))
if lineNum>ubound(temparray)+1 then
exit function
else
FSOlinedit = temparray(lineNum-1)
end if
end if
end function
19.使用FSO写文件某一行的函数
function FSOlinewrite(filename,lineNum,Linecontent)
if linenum < 1 then exit function
dim fso,f,temparray,tempCnt
set fso = server.CreateObject("scripting.filesystemobject")
if not fso.fileExists(server.mappath(filename)) then exit function
set f = fso.opentextfile(server.mappath(filename),1)
if not f.AtEndofStream then
tempcnt = f.readall
f.close
temparray = split(tempcnt,chr(13)&chr(10))
if lineNum>ubound(temparray)+1 then
exit function
else
temparray(lineNum-1) = lineContent
end if
tempcnt = join(temparray,chr(13)&chr(10))
set f = fso.createtextfile(server.mappath(filename),true)
f.write tempcnt
end if
f.close
set f = nothing
end function
20.使用FSO添加文件新行的函数
function FSOappline(filename,Linecontent)
dim fso,f
set fso = server.CreateObject("scripting.filesystemobject")
if not fso.fileExists(server.mappath(filename)) then exit function
set f = fso.opentextfile(server.mappath(filename),8,1)
f.write chr(13)&chr(10)&Linecontent
f.close
set f = nothing
end function
21.读文件最后一行的函数
function FSOlastline(filename)
dim fso,f,temparray,tempcnt
set fso = server.CreateObject("scripting.filesystemobject")
if not fso.fileExists(server.mappath(filename)) then exit function
set f = fso.opentextfile(server.mappath(filename),1)
if not f.AtEndofStream then
tempcnt = f.readall
f.close
set f = nothing
temparray = split(tempcnt,chr(13)&chr(10))
FSOlastline = temparray(ubound(temparray))
end if
end function 




ServerVariables 集合检索预定的环境变量。

语法
Request.ServerVariables (server environment variable)

参数
服务器环境变量
指定要检索的服务器环境变量名。可以使用下面列出的值。变量 说明
ALL_HTTP 客户端发送的所有 HTTP 标题文件。
ALL_RAW 检索未处理表格中所有的标题。ALL_RAW 和 ALL_HTTP 不同,ALL_HTTP 在标题文件名前面放置 HTTP_ prefix,并且标题名称总是大写的。使用 ALL_RAW 时,标题名称和值只在客户端发送时才出现。
APPL_MD_PATH 检索 ISAPI DLL 的 (WAM) Application 的元数据库路径。
APPL_PHYSICAL_PATH 检索与元数据库路径相应的物理路径。IIS 通过将 APPL_MD_PATH 转换为物理(目录)路径以返回值。
AUTH_PASSWORD 该值输入到客户端的鉴定对话中。只有使用基本鉴定时,该变量才可用。
AUTH_TYPE 这是用户访问受保护的脚本时,服务器用于检验用户的验证方法。
AUTH_USER 未被鉴定的用户名。
CERT_COOKIE 客户端验证的唯一 ID,以字符串方式返回。可作为整个客户端验证的签字。
CERT_FLAGS 如有客户端验证,则 bit0 为 1。
如果客户端验证的验证人无效(不在服务器承认的 CA 列表中),bit1 被设置为 1。

CERT_ISSUER 用户验证中的颁布者字段(O=MS,OU=IAS,CN=user name,C=USA)。
CERT_KEYSIZE 安全套接字层连接关键字的位数,如 128。
CERT_SECRETKEYSIZE 服务器验证私人关键字的位数。如 1024。
CERT_SERIALNUMBER 用户验证的序列号字段。
CERT_SERVER_ISSUER 服务器验证的颁发者字段。
CERT_SERVER_SUBJECT 服务器验证的主字段。
CERT_SUBJECT 客户端验证的主字段。
CONTENT_LENGTH 客户端发出内容的长度。
CONTENT_TYPE 内容的数据类型。同附加信息的查询一起使用,如 HTTP 查询 GET、 POST 和 PUT。
GATEWAY_INTERFACE 服务器使用的 CGI 规格的修订。格式为 CGI/revision。
HTTP_<HeaderName> HeaderName 存储在标题文件中的值。未列入该表的标题文件必须以 HTTP_ 作为前缀,以使 ServerVariables 集合检索其值。
注意 服务器将 HeaderName 中的下划线(_)解释为实际标题中的破折号。例如,如果您指定 HTTP_MY_HEADER,服务器将搜索以 MY-HEADER 为名发送的标题文件。

HTTPS 如果请求穿过安全通道(SSL),则返回 ON。如果请求来自非安全通道,则返回 OFF。
HTTPS_KEYSIZE 安全套接字层连接关键字的位数,如 128。
HTTPS_SECRETKEYSIZE 服务器验证私人关键字的位数。如 1024。
HTTPS_SERVER_ISSUER 服务器验证的颁发者字段。
HTTPS_SERVER_SUBJECT 服务器验证的主字段。
INSTANCE_ID 文本格式 IIS 实例的 ID。如果实例 ID 为 1,则以字符形式出现。使用该变量可以检索请求所属的(元数据库中)Web 服务器实例的 ID。
INSTANCE_META_PATH 响应请求的 IIS 实例的元数据库路径。
LOCAL_ADDR 返回接受请求的服务器地址。如果在绑定多个 IP 地址的多宿主机器上查找请求所使用的地址时,这条变量非常重要。
LOGON_USER 用户登录 Windows NT&reg; 的帐号。
PATH_INFO 客户端提供的额外路径信息。可以使用这些虚拟路径和 PATH_INFO 服务器变量访问脚本。如果该信息来自 URL,在到达 CGI 脚本前就已经由服务器解码了。
PATH_TRANSLATED PATH_INFO 转换后的版本,该变量获取路径并进行必要的由虚拟至物理的映射。
QUERY_STRING 查询 HTTP 请求中问号(?)后的信息。
REMOTE_ADDR 发出请求的远程主机的 IP 地址。
REMOTE_HOST 发出请求的主机名称。如果服务器无此信息,它将设置为空的 MOTE_ADDR 变量。
REMOTE_USER 用户发送的未映射的用户名字符串。该名称是用户实际发送的名称,与服务器上验证过滤器修改过后的名称相对。
REQUEST_METHOD 该方法用于提出请求。相当于用于 HTTP 的 GET、HEAD、POST 等等。
SCRIPT_NAME 执行脚本的虚拟路径。用于自引用的 URL。
SERVER_NAME 出现在自引用 UAL 中的服务器主机名、DNS 化名或 IP 地址。
SERVER_PORT 发送请求的端口号。
SERVER_PORT_SECURE 包含 0 或 1 的字符串。如果安全端口处理了请求,则为 1,否则为 0。
SERVER_PROTOCOL 请求信息协议的名称和修订。格式为 protocol/revision 。
SERVER_SOFTWARE 应答请求并运行网关的服务器软件的名称和版本。格式为 name/version 。
URL 提供 URL 的基本部分。


注释
如果客户端发送的标题文件在上述表格中找不到,可以在调用 Request.ServerVariables 中给标题文件名加上 HTTP_ 的前缀以检索其值。例如,如果客户端发送标题文件

SomeNewHeader:SomeNewValue

您可以通过使用下面的语法检索 SomeNewValue

<% Request.ServerVariables("HTTP_SomeNewHeader") %>

您可使用重述符以循环遍历所有的服务器变量名。例如,使用下面的脚本打印出所有的服务器名。

<TABLE>
<TR><TD><B>Server Variable</B></TD><TD><B>Value</B></TD></TR>
<% For Each name In Request.ServerVariables %>
<TR><TD> <%= name %> </TD><TD> <%= Request.ServerVariables(name) %> </TD></TR>
</TABLE>
<% Next %>

示例
下面的例子使用 Request 对象显示一些服务器变量。

<HTML>
<!-- This example displays the content of several ServerVariables. -->
ALL_HTTP server variable =
<%= Request.ServerVariables("ALL_HTTP") %> <BR>
CONTENT_LENGTH server variable =
<%= Request.ServerVariables("CONTENT_LENGTH") %> <BR>
CONTENT_TYPE server variable =
<%= Request.ServerVariables("CONTENT_TYPE") %> <BR>
QUERY_STRING server variable =
<%= Request.ServerVariables("QUERY_STRING") %> <BR>
SERVER_SOFTWARE server variable =
<%= Request.ServerVariables("SERVER_SOFTWARE") %> <BR>
</HTML>

下一个示例使用 ServerVariables 集合将服务器名插入一个超文本链接。

<A HREF = "http://<%= Request.ServerVariables("SERVER_NAME") %>
/scripts/MyPage.asp">Link to MyPage.asp</A>


窗口在设定的时间内关闭
<SCRIPT LANGUAGE="JavaScript">
<!--
function a(){
window.opener=null;
window.close();
}
setTimeout("a()",6000);
//-->
</SCRIPT>

首页 图片消失
<script language="javascript">
function kick()
{
if(div1.style.pixelTop>-140)
div1.style.pixelTop=div1.style.pixelTop-1
}

function kiss()
{
var p=setInterval("kick()",30);
}

function on_it()
{
div1.style.pixelTop=0;
div1.style.pixelTop=0;
}
</script>

<body onLoad="kiss()"  style="margin:0;0;0;0 ">
<div style="top:0px; left:0px; position:absolute; background:red; width:531px; height:120; z-index: 0;" id="div1"  onMouseOver="on_it()"><img src="aa.jpg" width="179" height="146"><img src="dd.jpg" width="176" height="146"><img src="ff.jpg" width="175" height="146"></div>

</body>

自动提交
<body id="b"> <form action="arr.asp" method="post"  name="form1">   <input type="text" name="textfield" value="454">   <input type="submit" name="Submit" value="提交"> </form> <script language="javascript" type="text/javascript"> function b.onload() { document.form1.submit(); } </script> </body> 
自动提交 ok

<body onLoad="go_time()"> <form name="form1" method="post" action="news.html">  <input type="hidden" name="textfield">  <input type="hidden" name="textfield2"> </form> <script language="javascript" type="text/javascript"> function go_it() { document.form1.submit(); } // function go_time() { var p=setTimeout("go_it()",3000); }  </script>



我也来贴一个,条型码code-128 c类编码,调用produceHTML(str),code-128 c类的编码规则,自己去查。
这个也有php版,是国外的一个人写的,不过他的php版有一些bug,我从他的php版改来的,写得乱七八糟的,大家自己整理。

<%
            ascii= " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[/]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   dim arr128(106)
   arr128(0)  = "212222"'c类有自己的规则,这里的数字是表示白黑条的宽度
   arr128(1)  = "222122"
   arr128(2)  = "222221"
   arr128(3)  = "121223"
   arr128(4)  = "121322"
   arr128(5)  = "131222"
   arr128(6)  = "122213"
   arr128(7)  = "122312"
   arr128(8)  = "132212"
   arr128(9)  = "221213"
   arr128(10)  = "221312"
   arr128(11)  = "231212"
   arr128(12)  = "112232"
   arr128(13)  = "122132"
   arr128(14)  = "122231"
   arr128(15)  = "113222"
   arr128(16)  = "123122"
   arr128(17)  = "123221"'1
   arr128(18)  = "223211"
   arr128(19)  = "221132"
   arr128(20)  = "221231"
   arr128(21)  = "213212"
   arr128(22)  = "223112"
   arr128(23)  = "312131"
   arr128(24)  = "311222"
   arr128(25)  = "321122"'9
   arr128(26)  = "321221"
   arr128(27)  = "312212"
   arr128(28)  = "322112"
   arr128(29)  = "322211"
   arr128(30)  = "212123"
   arr128(31)  = "212321"
   arr128(32)  = "232121"
   arr128(33)  = "111323"
   arr128(34)  = "131123"
   arr128(35)  = "131321"
   arr128(36)  = "112313"
   arr128(37)  = "132113"
   arr128(38)  = "132311"
   arr128(39)  = "211313"
   arr128(40)  = "231113"
   arr128(41)  = "231311"
   arr128(42)  = "112133"
   arr128(43)  = "112331"
   arr128(44)  = "132131"
   arr128(45)  = "113123"
   arr128(46)  = "113321"
   arr128(47)  = "133121"
   arr128(48)  = "313121"
   arr128(49)  = "211331"
   arr128(50)  = "231131"
   arr128(51)  = "213113"
   arr128(52)  = "213311"
   arr128(53)  = "213131"
   arr128(54)  = "311123"
   arr128(55)  = "311321"
   arr128(56)  = "331121"
   arr128(57)  = "312113"
   arr128(58)  = "312311"
   arr128(59)  = "332111"
   arr128(60)  = "314111"
   arr128(61)  = "221411"
   arr128(62)  = "431111"
   arr128(63)  = "111224"
   arr128(64)  = "111422"
   arr128(65)  = "121124"
   arr128(66)  = "121421"
   arr128(67)  = "141122"
   arr128(68)  = "141221"
   arr128(69)  = "112214"
   arr128(70)  = "112412"
   arr128(71)  = "122114"
   arr128(72)  = "122411"
   arr128(73)  = "142112"
   arr128(74)  = "142211"
   arr128(75)  = "241211"
   arr128(76)  = "221114"
   arr128(77)  = "413111"
   arr128(78)  = "241112"
   arr128(79)  = "134111"
   arr128(80)  = "111242"
   arr128(81)  = "121142"
   arr128(82)  = "121241"
   arr128(83)  = "114212"
   arr128(84)  = "124112"
   arr128(85)  = "124211"
   arr128(86)  = "411212"
   arr128(87)  = "421112"
   arr128(88)  = "421211"
   arr128(89)  = "212141"
   arr128(90)  = "214121"
   arr128(91)  = "412121"
   arr128(92)  = "111143"
   arr128(93)  = "111341"
   arr128(94)  = "131141"
   arr128(95)  = "114113"
   arr128(96)  = "114311"
   arr128(97)  = "411113"
   arr128(98)  = "411311"
   arr128(99)  = "113141"
   arr128(100)  = "114131"
   arr128(101)  = "311141"
   arr128(102)  = "411131"
   arr128(103)  = "211412"
   arr128(104)  = "211214"
   arr128(105)  = "211232"
   arr128(106)  = "2331112"
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
   function produceArray(intext)
   'response.write  intext
   'response.end
   total = 104
   ' START
   ticketArray= "104"
   onChar=0
   ' GO THRU ARRAY GET LETTERS
   for z=1 to len(intext)
    pos = instr(ascii,mid(intext,z,1))
    '/// SKIP, NOT FOUND CHARS,continue loop
    'text=text&mid(intext,i,i)&"<br>"

    onChar=onChar+1
    ticketArray = ticketArray&","&pos 
    total = total+( onChar * pos )
   next
    'response.write text
    'response.end()
   '/// CHECK CHAR
   ticketArray =ticketArray&","&( total mod 103 )
   
   ' END
   ticketArray=ticketArray&",106"
  
   produceArray=ticketArray
   
  end function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
function produceHTML(givetext)
   alignment=0
   fheight=30
   fwidth=1
   bImg="a.jpg"'a与b的宽都为1,a为黑色,b为白色
   wImg="b.jpg"
   dim color(1)
   ticketArray = produceArray(givetext)

   ticketArray=split(ticketArray,",")
   html ="<table cellpadding=5 cellspacing=0 border=0 bgcolor=white align='left'><tr><td>"
   
   '/// ARRAY OF IMAGES
   color(0) = bImg
   color(1) = wImg
   
   ' OUTPUT HTML
   'if ( is_array($ticketArray) ) {
   
    for each ele in ticketArray
    
     bon = 0
    
     info = arr128(int(ele))        
     
     for i=1 to len(info)
       
      if alignment=0 then
       html = html&"<img src='"&color(bon)&"'  height='"&fheight&"' width = '"&int(mid(info,i,1)*fwidth)&"'>"
         else
       html = html&"<img src='"&color(bon)&"'  width='"&fheight&"'  height = '"&int(mid(info,i,1)*fwidth)&"'>"
      end if
      if bon=0 then
      bon=1
      else
      bon=0
      end if
     next
      
    next

   html = html&"</td></tr></table>"
   
   produceHTML=html
end function
%>


ASP操作Excel技术总结


目录
一、  环境配置
二、  ASP对Excel的基本操作
三、  ASP操作Excel生成数据表
四、  ASP操作Excel生成Chart图
五、  服务器端Excel文件浏览、下载、删除方案
六、  附录

正文
一、  环境配置
服务器端的环境配置从参考资料上看,微软系列的配置应该都行,即:
1.Win9x+PWS+Office
2.Win2000 Professional+PWS+Office
3.Win2000 Server+IIS+Office
目前笔者测试成功的环境是后二者。Office的版本没有特殊要求,考虑到客户机配置的不确定性和下兼容特性,建议服务器端Office版本不要太高,以防止客户机下载后无法正确显示。
服务器端环境配置还有两个偶然的发现是:
1.  笔者开发机器上原来装有金山的WPS2002,结果Excel对象创建始终出现问题,卸载WPS2002后,错误消失。
2.  笔者开发ASP代码喜欢用FrontPage,结果发现如果FrontPage打开(服务器端),对象创建出现不稳定现象,时而成功时而不成功。扩展考察后发现,Office系列的软件如果在服务器端运行,则Excel对象的创建很难成功。
服务器端还必须要设置的一点是COM组件的操作权限。在命令行键入“DCOMCNFG”,则进入COM组件配置界面,选择Microsoft Excel后点击属性按钮,将三个单选项一律选择自定义,编辑中将Everyone加入所有权限。保存完毕后重新启动服务器。
客户端的环境配置没发现什么特别讲究的地方,只要装有Office和IE即可,版本通用的好象都可以。


二、  ASP对Excel的基本操作
1、  建立Excel对象
set objExcelApp = CreateObject("Excel.Application")
objExcelApp.DisplayAlerts = false    不显示警告
objExcelApp.Application.Visible = false    不显示界面
2、  新建Excel文件
objExcelApp.WorkBooks.add
set objExcelBook = objExcelApp.ActiveWorkBook
set objExcelSheets = objExcelBook.Worksheets
set objExcelSheet = objExcelBook.Sheets(1)
3、  读取已有Excel文件
strAddr = Server.MapPath(".")
objExcelApp.WorkBooks.Open(strAddr & "/Templet/Table.xls")
set objExcelBook = objExcelApp.ActiveWorkBook
set objExcelSheets = objExcelBook.Worksheets
set objExcelSheet = objExcelBook.Sheets(1)
4、  另存Excel文件
objExcelBook.SaveAs strAddr & "/Temp/Table.xls"
5、  保存Excel文件
objExcelBook.Save    (笔者测试时保存成功,页面报错。)
6、  退出Excel操作
objExcelApp.Quit  一定要退出
set objExcelApp = Nothing


三、  ASP操作Excel生成数据表
1、  在一个范围内插入数据
objExcelSheet.Range("B3:k3").Value = Array("67", "87", "5", "9", "7", "45", "45", "54", "54", "10")
2、  在一个单元格内插入数据
objExcelSheet.Cells(3,1).Value="Internet Explorer"
3、  选中一个范围
4、  单元格左边画粗线条
5、  单元格右边画粗线条
6、  单元格上边画粗线条
7、  单元格下边画粗线条
8、  单元格设定背景色
9、  合并单元格
10、  插入行
11、  插入列


四、  ASP操作Excel生成Chart图
1、  创建Chart图
objExcelApp.Charts.Add
2、  设定Chart图种类
objExcelApp.ActiveChart.ChartType = 97
注:二维折线图,4;二维饼图,5;二维柱形图,51
3、  设定Chart图标题
objExcelApp.ActiveChart.HasTitle = True
objExcelApp.ActiveChart.ChartTitle.Text = "A test Chart"
4、  通过表格数据设定图形
objExcelApp.ActiveChart.SetSourceData objExcelSheet.Range("A1:k5"),1
5、  直接设定图形数据(推荐)
objExcelApp.ActiveChart.SeriesCollection.NewSeries
objExcelApp.ActiveChart.SeriesCollection(1).Name = "=""333"""
objExcelApp.ActiveChart.SeriesCollection(1).Values = "="
6、  绑定Chart图
objExcelApp.ActiveChart.Location 1
7、  显示数据表
objExcelApp.ActiveChart.HasDataTable = True
8、  显示图例
objExcelApp.ActiveChart.DataTable.ShowLegendKey = True


五、  服务器端Excel文件浏览、下载、删除方案
浏览的解决方法很多,“Location.href=”,“Navigate”,“Response.Redirect”都可以实现,建议用客户端的方法,原因是给服务器更多的时间生成Excel文件。
下载的实现要麻烦一些。用网上现成的服务器端下载组件或自己定制开发一个组件是比较好的方案。另外一种方法是在客户端操作Excel组件,由客户端操作服务器端Excel文件另存至客户端。这种方法要求客户端开放不安全ActiveX控件的操作权限,考虑到通知每个客户将服务器设置为可信站点的麻烦程度建议还是用第一个方法比较省事。
删除方案由三部分组成:
A:  同一用户生成的Excel文件用同一个文件名,文件名可用用户ID号或SessionID号等可确信不重复字符串组成。这样新文件生成时自动覆盖上一文件。
B:  在Global.asa文件中设置Session_onEnd事件激发时,删除这个用户的Excel暂存文件。
C:  在Global.asa文件中设置Application_onStart事件激发时,删除暂存目录下的所有文件。
注:建议目录结构 /Src 代码目录 /Templet 模板目录 /Temp 暂存目录


六、  附录
出错时Excel出现的死进程出现是一件很头疼的事情。在每个文件前加上“On Error Resume Next”将有助于改善这种情况,因为它会不管文件是否产生错误都坚持执行到“Application.Quit”,保证每次程序执行完不留下死进程。


评论
# re: ASP操作Excel技术总结   
这个程序一共由三个文件构成,第一个文件的文件名为:toexcel.asp是主文件,内容如下:

<%

'前面是和来链接到数据库,请自行书写相关语句,此处略过

sql="select * from [tx_use]" '这里是要输出EXCEL的查询语句,如 "SESECT * FORM CAI Where 性别='女'"
filename="excel.xls" ' 要输出的EXCEL文件的文件名, 你只要改以上两句就行了,其它的都不要改.

'你只要修改以上两变量就行了.其它的我都做好了.

call toexcel(FILENAME,sql)
set conn=nothing

function ReadText(FileName) '这是一个用于读出文件的函数
set adf=server.CreateObject("Adodb.Stream")
with adf
.Type=2
.LineSeparator=10
.Open
.LoadFromFile (server.MapPath(FileName))
.Charset="GB2312"
.Position=2
ReadText=.ReadText
.Cancel()
.Close()
end with
set ads=nothing
end function

sub SaveText(FileName,Data) '这是一个用于写文件的函数
set fs= createobject("scripting.filesystemobject")
set ts=fs.createtextfile(server.MapPath(FileName),true)
ts.writeline(data)
ts.close
set ts=nothing
set fs=nothing
end sub

sub toexcel(filename,sql) '这是一个根据SQL语句和FILENAME生成EXCEL文件
Set rs=Server.CreateObject("ADODB.RecordSet")
rs.Open sql,conn,1,3
TOEXCELLR="<table width='100%'><tr >"
set myfield=rs.fields
dim fieldname(50)
for i=0 to myfield.count-1
toexcellr=toexcellr&"<td class=xl24>"&MYFIELD(I).NAME&"</td>"
fieldname(i)=myfield(i).name
if myfield(i).type=135 then datename=datename&myfield(i).name&","
next
toexcellr=toexcellr&"</tr>"
do while not rs.eof
toexcellr=toexcellr&"<tr>"
for i=0 to myfield.count-1
if instr(datename,fieldname(i)&",")<>0 then
if not isnull(rs(fieldname(i))) then
TOEXCELLR=TOEXCELLR&"<td class=xl25 ><p align='left'>"&formatdatetime(rs(fieldname(i)),2)&"</p></td>"
else
TOEXCELLR=TOEXCELLR&"<td class=xl25 ><p align='left'> </p></td>"
end if
else
TOEXCELLR=TOEXCELLR&"<td class=xl24 >"&rs(fieldname(i))&"</td>"
end if
next
toexcellr=toexcellr&"</tr>"
rs.movenext
loop
toexcellr=toexcellr&"</table>"
tou=readtext("tou.txt")
di=readtext("di.txt")
toexcellr=tou&toexcellr&di
call savetext(filename,toexcellr)
end sub
%>
<html>
<head>
<meta http-equiv="refresh" content="3;URL=<%=filename%>">
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>正在生成EXLCE文件</title>
</head>
<BODY>
正在生成EXLCE文件....
</BODY>
</HTML>

**************第二个文件名为:di.txt 内容如下:

<table x:str border=0 cellpadding=0 cellspacing=0 width=288 style='border-collapse:
collapse;table-layout:fixed;width:216pt'>
<![if supportMisalignedColumns]>
<tr height=0 style='display:none'>
<td width=72 style='width:54pt'></td>
<td width=72 style='width:54pt'></td>
<td width=72 style='width:54pt'></td>
<td width=72 style='width:54pt'></td>
</tr>
<![endif]>
</table>

************第三个文件的文件名为:tou.TXT 内容如下:


<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">

<head>
<meta http-equiv=Content-Type content="text/html; charset=GB2312">
<meta name=ProgId content=Excel.Sheet>
<meta name=Generator content="Microsoft Excel 9">
<link rel=File-List href="./222.files/filelist.xml">
<link rel=Edit-Time-Data href="./222.files/editdata.mso">
<link rel=OLE-Object-Data href="./222.files/oledata.mso">
<!--[if gte mso 9]><xml>
<DocumentProperties>
<Author>xky</Author>
<LastAuthor>xky</LastAuthor>
<Created>2002-05-27T17:51:00Z</Created>
<LastSaved>2002-06-22T10:03:03Z</LastSaved>
<Company>zydn</Company>
<Version>9.2812</Version>
</DocumentProperties>
<OfficeDocumentSettings>
<DownloadComponents/>
<LocationOfComponents HRef="file:///E:/msowc.cab"/>
</OfficeDocumentSettings>
</xml><![endif]-->
<style>
<!--table
{mso-displayed-decimal-separator:"/.";
mso-displayed-thousand-separator:"/,";}
@page
{margin:1.0in .75in 1.0in .75in;
mso-header-margin:.5in;
mso-footer-margin:.5in;}
tr
{mso-height-source:auto;
mso-ruby-visibility:none;}
col
{mso-width-source:auto;
mso-ruby-visibility:none;}
br
{mso-data-placement:same-cell;}
.style0
{mso-number-format:General;
text-align:general;
vertical-align:bottom;
white-space:nowrap;
mso-rotate:0;
mso-background-source:auto;
mso-pattern:auto;
color:windowtext;
font-size:9.0pt;
font-weight:400;
font-style:normal;
text-decoration:none;
font-family:宋体;
mso-generic-font-family:auto;
mso-font-charset:134;
border:none;
mso-protection:locked visible;
mso-style-name:常规;
mso-style-id:0;}
td
{mso-style-parent:style0;
padding-top:1px;
padding-right:1px;
padding-left:1px;
mso-ignore:padding;
color:windowtext;
font-size:9.0pt;
font-weight:400;
font-style:normal;
text-decoration:none;
font-family:宋体;
mso-generic-font-family:auto;
mso-font-charset:134;
mso-number-format:General;
text-align:general;
vertical-align:bottom;
border:none;
mso-background-source:auto;
mso-pattern:auto;
mso-protection:locked visible;
white-space:nowrap;
mso-rotate:0;}
.xl24
{mso-style-parent:style0;
border:.5pt solid windowtext;}
.xl25
{mso-style-parent:style0;
mso-number-format:"Long Date";
text-align:left;
border:.5pt solid windowtext;}
ruby
{ruby-align:left;}
rt
{color:windowtext;
font-size:9.0pt;
font-weight:400;
font-style:normal;
text-decoration:none;
font-family:宋体;
mso-generic-font-family:auto;
mso-font-charset:134;
mso-char-type:none;
display:none;}
-->
</style>
<!--[if gte mso 9]><xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>Sheet1</x:Name>
<x:WorksheetOptions>
<x:DefaultRowHeight>225</x:DefaultRowHeight>
<x:Print>
<x:ValidPrinterInfo/>
<x:PaperSizeIndex>9</x:PaperSizeIndex>
<x:HorizontalResolution>-3</x:HorizontalResolution>
<x:VerticalResolution>0</x:VerticalResolution>
</x:Print>
<x:Selected/>
<x:Panes>
<x:Pane>
<x:Number>3</x:Number>
<x:ActiveRow>24</x:ActiveRow>
<x:ActiveCol>5</x:ActiveCol>
</x:Pane>
</x:Panes>
<x:ProtectContents>False</x:ProtectContents>
<x:ProtectObjects>False</x:ProtectObjects>
<x:ProtectScenarios>False</x:ProtectScenarios>
</x:WorksheetOptions>
</x:ExcelWorksheet>
<x:ExcelWorksheet>
<x:Name>Sheet2</x:Name>
<x:WorksheetOptions>
<x:DefaultRowHeight>225</x:DefaultRowHeight>
<x:ProtectContents>False</x:ProtectContents>
<x:ProtectObjects>False</x:ProtectObjects>
<x:ProtectScenarios>False</x:ProtectScenarios>
</x:WorksheetOptions>
</x:ExcelWorksheet>
<x:ExcelWorksheet>
<x:Name>Sheet3</x:Name>
<x:WorksheetOptions>
<x:DefaultRowHeight>225</x:DefaultRowHeight>
<x:ProtectContents>False</x:ProtectContents>
<x:ProtectObjects>False</x:ProtectObjects>
<x:ProtectScenarios>False</x:ProtectScenarios>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
<x:WindowHeight>6600</x:WindowHeight>
<x:WindowWidth>12000</x:WindowWidth>
<x:WindowTopX>0</x:WindowTopX>
<x:WindowTopY>1395</x:WindowTopY>
<x:ProtectStructure>False</x:ProtectStructure>
<x:ProtectWindows>False</x:ProtectWindows>
</x:ExcelWorkbook>
</xml><![endif]-->
</head>

<body link=blue vlink=purple>




如何在ASP中实现网络打印功能
使用到的技术:
ASP,WSH,VBScript
文件ASPPrint.asp代码如下:

 
  <%@ Language=VBScript %>
  <%
  Option Explicit

  Dim strSubmit         'Form中用来保存提交按钮的值
  Dim strPrinterPath    'Form中保存网络打印机路径的值
  Dim strUsername       'Form中用户名的值
  Dim strPassword       'Form中密码的值
  Dim strMessage        'Form打印内容的值
  Dim objFS             'VBScript中的文件系统对象
  Dim objWSHNet         'WSH中的网络对象
  Dim objPrinter        '打印对象

  strSubmit = Request.Form("Submit")
  %>

  <HTML>
  <HEAD>
  <META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
  </HEAD>
  <BODY>

  <%
  If strSubmit = "" Then
  %>

  注意的是:
      由于我是演示起见,其中有关NT的帐号和密码都是使用了不加密的手段在
ASP中传递的
  真正的运用中应该对该登录过程进行安全处理。
  <FORM action="ASPPrint.asp" method=POST id=form name=form>
     <TABLE WIDTH=100% ALIGN=center BORDER=0 CELLSPACING=1 CELLPADDING
=1>
        <TR>
           <TD ALIGN=right NOWRAP>网络打印机路径:</TD>
           <TD ALIGN=left NOWRAP><INPUT type="text" id=printerpath nam
e=printerpath 
              value="//< Domain >/< Printer >"></TD>
        </TR>
        <TR>
           <TD ALIGN=right NOWRAP>登录帐号:</TD>
           <TD ALIGN=left NOWRAP><INPUT type="text" id=username name=u
sername 
              value="<% = strUsername %>"></TD>
        </TR>
        <TR>
           <TD ALIGN=right NOWRAP>登录口令:</TD>
           <TD ALIGN=left NOWRAP><INPUT type="password" id=password 
              name=password></TD>
        </TR>
        <TR>
           <TD ALIGN=right NOWRAP>请输入你想打印的文字:</TD>
           <TD ALIGN=left NOWRAP><TEXTAREA rows=2 cols=20 id=message 

              name=message></TEXTAREA></TD>
        </TR>
        <TR>
           <TD ALIGN=right NOWRAP> </TD>
           <TD ALIGN=left NOWRAP><INPUT type="submit" value="Submit" 

              id=submit name=submit></TD>
        </TR>
     </TABLE>
  </FORM>

  当以上信息被提交后,就可以按照下面的代码进行打印了。
  <%
  Else
     ' 从form中取得响应信息。
     strPrinterPath = Request.Form("printerpath")
     strUsername = Request.Form("username")
     strPassword = Request.Form("password")
     strMessage = Request.Form("message")

  We will now use the VBScript FileSystemObject object and the WSH Net
work object. The Network object will
  give us the methods we need to open a printer connection, and the Fi
leSystemObject will allow us to stream our
  output to the printer. We create these objects in the following code
 example: 

     Set objFS = CreateObject("Scripting.FileSystemObject")
     Set objWSHNet = CreateObject("WScript.Network")
     ' 使用WSH连接网络打印机
     objWSHNet.AddPrinterConnection "LPT1", strPrinterPath, False, str
Username, strPassword
     ' 使用文件系统对象将打印设备作为一个文件使用
     Set objPrinter = objFS.CreateTextFile("LPT1:", True)
     ' 给打印设备送出文本
     objPrinter.Write(strMessage)
     '关闭打印设备对象并进行错误陷阱处理
     On Error Resume Next
     objPrinter.Close
     ' 如果发生错误,关闭打印连接,并输出错误信息
     If Err Then
        Response.Write ("Error # " & CStr(Err.Number) & " " & Err.Desc
ription)
        Err.Clear    
     Else
        ' 操作成功,输出确认信息
        Response.Write("<CENTER>")
        Response.Write("<TABLE WIDTH=100% ALIGN=center BORDER=0 CELLSP
ACING=1 CELLPADDING=1>")
        Response.Write("<TR><TD ALIGN=RIGHT><B>打印消息送出:</B></TD>"
)
        Response.Write("<TD ALIGN=LEFT>" & strMessage & "</TD></TR>")

        Response.Write("<TR><TD ALIGN=RIGHT><B>网络打印机路径:</B></TD
>")
        Response.Write("<TD ALIGN=LEFT>" & strPrinterPath & "</TD></TR
>")
        Response.Write("<TR><TD ALIGN=RIGHT><B>登录帐号:</B></TD>")
        Response.Write("<TD ALIGN=LEFT>" & strUsername & "</TD></TR>")

        Response.Write("</TABLE>")
        Response.Write("</CENTER>")
     End If
     ' 取消打印连接
     objWSHNet.RemovePrinterConnection "LPT1:"
     Set objWSHNet  = Nothing
     Set objFS      = Nothing
     Set objPrinter = Nothing
  End If
  %>
  </BODY>
  </HTML>
 


response_buffer.asp
<%'response.buffer=true%>
<a href="a">a</a>
<%response.redirect "request_form.htm"%>

效果:
①.当关闭IIS的缓冲功能,访问该页面时出错
a
答复对象 错误 'ASP 0156 : 80004005'
头错
/course/response_buffer.asp,行3
HTTP 头已经写入到 客户浏览器。任何 HTTP 头的修改必须在写入页内容之前。
②.当关闭IIS的缓冲功能,去掉文件第一行的注释,则页面重定向成功
③.当打开IIS的缓冲功能,无论是否去掉文件第一行的注释,页面重定向都成功



问题:如何保护自己的ASP源代码不泄露?

  答:下载微软的windows script encoder,对ASP的脚本和客户端javascript、vbscript脚本进行加密。客户端脚本加密后,只有ie5以上的版本才能执行,服务器端脚本加密后,只有服务器上安装有script engine 5(装ie5即可)才能解释执行。

  问题:为什么global.asa文件总是不起作用?

  答:只有把global.asa文件放在web发布目录某个站点的根目录下它才有效,放在发布目录的某个子目录下不起作用。另外,也可以使用iis4的internet service manager把某个子目录设置为站点。

  问题:为什么ASP文件总不解释执行?

  答:在iis服务器上没有给ASP文件以脚本解释的权限,所以ASP文件没有被web服务器作为脚本代码进行解释执行,而被当成一般页面文件了。建议在web发布目录中建立一个ASP目录,把所有ASP文件存放在此目录下,把ASP目录赋予脚本解释权限。

  问题:ASP文件中使用response.redirect(url)时导致错误“the http headers are already written to the client browser. any http header modifications must be made before writing page content”,请问如何解决?

  答:此错误为http标题在写入页内容之后,写到了客户浏览器中。任何http标题的修改必须在写入页内容之前进行,解决的方法为在ASP文件最开头加入response.buffer = true,在文件的结尾加入response.flush。

  问题:为什么session有时候会消失?

  答:session很像临时的cookie,只是其信息保存在服务器上(客户机上保存的是sessionid)。session变量消失有几种可能,如:使用者的浏览器不接受cookie,因为session依赖于cookie才能跟踪用户;session在一段时间后过期了,缺省为20分钟,如果希望更改,可以通过设置microsoft management console的web directory→properties→virtual directory→application settings→configuration→app options→session timeout选项来改变session的超时时间,也可以在ASP脚本中设定,如session.timeout=60,可设定超时时间为60分钟。

  问题:怎样才能知道访问者的一些信息?

  答:通过request.servervariables("http—user—agent")获得访问者浏览器的类型;request.servervariables("remote—addr")可获得访问者的ip地址;而访问者的语言环境可通过request.servervariables("http—accept—language")来获得。

  问题:怎样才能将query string从一个ASP文件传送到另一个ASP文件?

  答:前一个ASP文件加入下列代码:response.redirect("second.ASP?"&request.servervariables("query—string"))即可。

  问题:ASP中如何控制cookies?

  答:若想写入cookies可用:response.cookies("待写入的coookies名称")=待写入数据。读取cookies则使用:读取数据=request.cookies("待读的cookies名称")。

  注意,写入cookies的response.cookies程序段必须放在〈html〉标记之前,且不可以有任何的其它html代码。另外,cookies中必须使用expires设定有效期,cookies才能真正地写入客户端硬盘中,否则只是临时的。

  问题:怎样实现用ASP发送邮件?

  答:用户需装上windows nt option pack的smtp service功能。实现代码如下:
  〈%
  set mail = server.createobject("cdonts.newmail")
  mail.to ="abc@xxx.com"
  mail.from ="yourmail@xxx.com"
  mail.subject ="主题"
  mail.body ="e-mail内容"
  mail.send
  %〉
  问题:ASP与数据库连接一定要在服务器端设置dsn吗?

  答:不一定,ASP与服务器的数据库连接有两种方法,一种为通过dsn建立连接,另一种不用dsn建立连接。通过dsn连接数据库需要服务器的系统管理员在服务器的控制面板中的odbc中设置一个dsn。如果没有在服务器上设置dsn,只要知道数据库文件名(比如access、paradox、foxpro的数据库)或者数据源名(如sqlserver的数据库)就可以访问数据库,直接提供连接所需的参数即可。

  连接代码如下:
  set conn=server.createobject("adodb.connection")
  connpath="dbq="&server.mappath("yourtable.mdb")
  conn.open"driver={microsoft access driver (.mdb)};"&connpath
  set rs=conn.execute("selectfrom authors")

  问题:如何从一页到另一页传递变量?

  答:用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〉

  用session来保存变量。

  〈%session("bh")= request.form ("bh")%〉

  用querystring保存变量。

  〈a herf="action.ASP?bh=10"〉查询〈/a〉
  〈%request. querystring ("bh")%〉
  问题:如何用ASP实现在线人数统计?

  答:在线人数是指一个时段内的访客人数统计,时间的长短是由设计者设定的。

  在这个时段内,各个不同ip访问本站点的总数,就是当前的线上人数。在ASP中,使用session对象来实现统计,实现代码如下:
  golobal.asa文件

  〈script language="vbscript"runat="server"〉
  sub session—onstart
  application("online")=application("online")+1
  end sub
  sub session—onend
  application("online")=application("online")-1
  end sub
  sub application—onstard
  application("online")=0
  end sub
  sub application—onend
  application("online")=0
  end sub
  〈/script〉

  online.ASP文件内容

  〈% tmp=application("online")
  tmp=cstr(tmp)
  dim disp(20)
  dim images(20)
  dbbits=len(tmp)
  for i= 1 to dbbits
  disp(i)=left(right(tmp,i),i-(i-1))
  next
  for i=dbbits to 1 step -1
  images(i)="〈img src="&"http://xxxx.com.cn/pic"&"/"&disp(i)&".gif〉"
  response.write"document.write(′"&images(i)&"′);"
  next %〉

  问题:ASP程序运行的时间如何计算?

  答:确定ASP程序的执行时间的代码如下所示:

  〈%
  dim t1,t2
  t1=now()

  ′被检测的ASP代码

  t2=now()
  response.write"运行这段ASP代码用了"&cstr(cdbl((t2-t1)*24*60*60))&"秒"
  %〉



一个操作读写已存在Excel文件的例子

Set xlApp = Server.CreateObject("Excel.Application")
strSource=FilePath & "Test.xls"'打开一个已经存在的test.xls文件,filepath为物理绝对路径
xlApp.Workbooks.Open(strSource)
Set xlbook = xlApp.ActiveWorkBook '打开book
Set xlsheet = xlbook.Worksheets(1) '打开其中的一个sheet  

xlsheet.cells(1,1).value="Test" '通过设置cell(i,j)里面的i,j来访问sheet里面任意一个cell
xlbook.Save  '保存该excel文件
xlbook.Saveas FilePath & "Test2.xls" '另存一个文件
  
Set xlsheet=nothing '一定要关闭,否则以后会一直存在一个无法释放的excel进程
Set xlbook=nothing
xlApp.quit

asp运行端的一些设置
1Excel文件所在的路径目录,要让IUSER_即asp运行的用户有读写权限,否则
会报错。
2服务器端还必须要设置COM组件的操作权限。在命令行键入“DCOMCNFG”,
进入COM组件配置界面,选择Microsoft Excel后点击属性按钮,将三个单选
项一律选择自定义,编辑中将Everyone加入所有权限。保存完毕后重新启动
服务器。



如何使用事务处理、存储过程和视图?

⑴.使用存储过程

①.定义好存储过程

Create PROCEDURE [output_1]
@sid int output
AS
set @sid=2

Create PROCEDURE [return_1]
(@user_name varchar(40),@password varchar(20))
AS
if exists(select id from user_info where user_name=@user_name and password=@password)
return 1
else
return 0

Create PROCEDURE [user_info_1]
(@user_name varchar(40),@password varchar(20))
AS
select id from user_info where user_name=@user_name and password=@password

Create PROCEDURE [user_info_2]
(@user_name varchar(40),@password varchar(20))
AS
SET XACT_ABORT ON
BEGIN TRANSACTION
delete from user_info where user_name=@user_name and password=@password
COMMIT TRANSACTION
SET XACT_ABORT OFF

Create PROCEDURE [user_info_3] AS
select * from user_info

②.在Asp中调用

use_proc.asp
<!-- #include virtual="/adovbs.inc" -->
<%
Set conn=Server.CreateObject("ADODB.Connection")
conn.Open "course_dsn","course_user","course_password"

'使用recordset调用带两个输入参数和返回纪录集的存储过程
'Create PROCEDURE [user_info_1]
'(@user_name varchar(40),@password varchar(20))
'AS
'select id from user_info where user_name=@user_name and password=@password
response.write "普通的调用方法:<br>"
set rs=server.createobject("adodb.recordset")
sql="user_info_1 '"&request.querystring("user_name")&"','"&request.querystring("password")&"'"
rs.open sql,conn,1,1
response.write rs("id")&"<br>"
rs.close

'使用recordset调用无输入参数,返回纪录集的存储过程,可以使用recordcount等属性
'Create PROCEDURE [user_info_3] AS
'select * from user_info
response.write "<br>返回纪录集,可以使用recordcount等属性:"
sql="exec user_info_3"
rs.open sql,conn,1,1
for i=1 to rs.recordcount
response.write "<br>"&rs("user_name")
rs.movenext
next
rs.close
set rs=nothing

'使用command调用带输出参数的存储过程
'Create PROCEDURE [output_1]
'@sid int output
'AS
'set @sid=2
response.write "<br><br>调用带输出参数的存储过程:<br>"
set cmd=server.createobject("adodb.command")
cmd.activeconnection=conn
cmd.commandtext = "output_1"
cmd.parameters.append cmd.createparameter("@sid",adinteger,adparamoutput)
cmd("@sid")=10
cmd.execute()
bbb=cmd("@sid")
response.write bbb&"<br>"
set cmd=nothing

'使用command调用带两个输入参数和返回值的存储过程
'Create PROCEDURE [return_1]
'(@user_name varchar(40))
'AS
'if exists(select id from user_info where user_name=@user_name)
'return 1
'else
'return 0
response.write "<br>调用带两个输入参数和返回值的存储过程:<br>"
set cmd=server.createobject("adodb.command")
cmd.activeconnection=conn
cmd.commandtype = adcmdstoredproc
cmd.commandtext = "return_1"
cmd.parameters.append cmd.createparameter("@return_value",adinteger,adparamreturnvalue)
cmd.parameters.append cmd.createparameter("@user_name",advarchar,adparaminput,40)
cmd.parameters.append cmd.createparameter("@password",advarchar,adparaminput,20)
cmd("@user_name")="tuth"
cmd("@password")="yyuyu"
cmd.execute()
rrr=cmd("@return_value")
response.write rrr
set cmd=nothing

conn.close
set conn=nothing
%>

效果:
访问http://10.1.43.238/course/use_proc.asp?user_name=ahyi&password=ttt时,出现如下

普通的调用方法:
12

返回纪录集,可以使用recordcount等属性:
ahyi
tet
tuth

调用带输出参数的存储过程:
2

调用带两个输入参数和返回值的存储过程:
1

注意:若存储过程无参数,则调用的sql语句直接为存储过程名,一个参数为“存储过程名 参数”,若是多个参数,则“存储过程名 参数1,参数2,……,参数n”;如果在sql语句中加入exec,则在返回的记录集中可以使用recordcount等属性;如果想获得存储过程的返回值或输出参数,可以使用command对象。

⑵.使用事务处理

①.Asp内嵌的事务支持

例子:
use_transaction_1.asp
<%
'Asp中使用事务
Set conn=Server.CreateObject("ADODB.Connection")
conn.Open "course_dsn","course_user","course_password"
conn.begintrans '开始事务

sql="delete from user_info"
set rs=server.createobject("adodb.recordset")
rs.open sql,conn,3,3
if conn.errors.count>0 then '有错误发生
conn.rollbacktrans '回滚
set rs=nothing
conn.close
set conn=nothing
response.write "交易失败,回滚至修改前的状态!"
response.end
else
conn.committrans '提交事务
set rs=nothing
conn.close
set conn=nothing
response.write "交易成功!"
response.end
end if
%>

②.数据库级的事务

i.创建存储过程

Create PROCEDURE [user_info_2]
(@user_name varchar(40),@password varchar(20))
AS
SET XACT_ABORT ON
BEGIN TRANSACTION
delete from user_info where user_name=@user_name and password=@password
COMMIT TRANSACTION
SET XACT_ABORT OFF

ii.在Asp中调用

use_transaction_2.asp
<%
Set conn=Server.CreateObject("ADODB.Connection")
conn.Open "course_dsn","course_user","course_password"

sql="user_info_2 '"&request.querystring("user_name")&"','"&request.querystring("password")&"'"

set rs=server.createobject("adodb.recordset")
rs.open sql,conn,1,1
set rs=nothing
conn.close
set conn=nothing
%>

讨论:两种方式的优劣?

⑶.使用视图
在数据库中定义好视图之后,在Asp中如同使用一个表一样来使用视图



各类型数据的导入与导出:
*******  导出到excel
EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:/temp1.xls -c -q -S"GNETDATA/GNETDATA" -U"sa" -P""'

/***********  导入Excel
select * from openrowset('MicroSoft.Jet.OleDB.4.0',
                         'Excel 5.0;HDR=yes;Database=c:/test.xls',sheet1$)
--------------------------------------------------------
Select *
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
  'Data Source="c:/test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions


Select cast(cast(科目编号 as numeric(10,2)) as nvarchar(255))+' ' 转换后的别名
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
  'Data Source="c:/test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions

/** 导入文本文件
EXEC master..xp_cmdshell 'bcp "dbname..tablename" in c:/DT.txt -c -Sservername -Usa -Ppassword'

/** 导出文本文件
EXEC master..xp_cmdshell 'bcp "dbname..tablename" out c:/DT.txt -c -Sservername -Usa -Ppassword'

EXEC master..xp_cmdshell 'bcp "Select * from dbname..tablename" queryout c:/DT.txt -c -Sservername -Usa -Ppassword'

导出到TXT文本,用逗号分开
exec master..xp_cmdshell 'bcp "库名..表名" out "d:/tt.txt" -c -t ,-U sa -P password'


BULK Insert 库名..表名
FROM 'c:/test.txt'
WITH (
    FIELDTERMINATOR = ';',
    ROWTERMINATOR = '/n'
)


--/* dBase IV文件
select * from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'dBase IV;HDR=NO;IMEX=2;DATABASE=C:/','select * from [客户资料4.dbf]')
--*/

--/* dBase III文件
select * from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'dBase III;HDR=NO;IMEX=2;DATABASE=C:/','select * from [客户资料3.dbf]')
--*/

--/* FoxPro 数据库
select * from openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;SourceType=DBF;SourceDB=c:/',
'select * from [aa.DBF]')
--*/

/**************导入DBF文件****************/
select * from openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;
SourceDB=e:/VFP98/data;
SourceType=DBF',
'select * from customer where country != "USA" order by country')
go
/***************** 导出到DBF ***************/
如果要导出数据到已经生成结构(即现存的)FOXPRO表中,可以直接用下面的SQL语句

insert into openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;SourceType=DBF;SourceDB=c:/',
'select * from [aa.DBF]')
select * from 表

说明:
SourceDB=c:/  指定foxpro表所在的文件夹
aa.DBF        指定foxpro表的文件名.

 


/*************导出到Access********************/
insert into openrowset('Microsoft.Jet.OLEDB.4.0',
   'x:/A.mdb';'admin';'',A表) select * from 数据库名..B表

/*************导入Access********************/
insert into B表 selet * from openrowset('Microsoft.Jet.OLEDB.4.0',
   'x:/A.mdb';'admin';'',A表)

 


 
 
 
*********************  导入 xml 文件

DECLARE @idoc int
DECLARE @doc varchar(1000)
--sample XML document
SET @doc ='
<root>
  <Customer cid= "C1" name="Janine" city="Issaquah">
      <Order oid="O1" date="1/20/1996" amount="3.5" />
      <Order oid="O2" date="4/30/1997" amount="13.4">Customer was very satisfied
      </Order>
   </Customer>
   <Customer cid="C2" name="Ursula" city="Oelde" >
      <Order oid="O3" date="7/14/1999" amount="100" note="Wrap it blue
             white red">
            <Urgency>Important</Urgency>
            Happy Customer.
      </Order>
      <Order oid="O4" date="1/20/1996" amount="10000"/>
   </Customer>
</root>
'
-- Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc

-- Execute a Select statement using OPENXML rowset provider.
Select *
FROM OPENXML (@idoc, '/root/Customer/Order', 1)
      WITH (oid     char(5),
            amount  float,
            comment ntext 'text()')
EXEC sp_xml_removedocument @idoc
 
邹健的
/********************导整个数据库*********************************************/

用bcp实现的存储过程


/*
实现数据导入/导出的存储过程
         根据不同的参数,可以实现导入/导出整个数据库/单个表
调用示例:
--导出调用示例
----导出单个表
exec file2table 'zj','','','xzkh_sa..地区资料','c:/zj.txt',1
----导出整个数据库
exec file2table 'zj','','','xzkh_sa','C:/docman',1

--导入调用示例
----导入单个表
exec file2table 'zj','','','xzkh_sa..地区资料','c:/zj.txt',0
----导入整个数据库
exec file2table 'zj','','','xzkh_sa','C:/docman',0

*/
if exists(select 1 from sysobjects where name='File2Table' and objectproperty(id,'IsProcedure')=1)
drop procedure File2Table
go
create procedure File2Table
@servername varchar(200)--服务器名
,@username varchar(200)--用户名,如果用NT验证方式,则为空''
,@password varchar(200)--密码
,@tbname varchar(500)--数据库.dbo.表名,如果不指定:.dbo.表名,则导出数据库的所有用户表
,@filename varchar(1000)--导入/导出路径/文件名,如果@tbname参数指明是导出整个数据库,则这个参数是文件存放路径,文件名自动用表名.txt
,@isout bit--1为导出,0为导入
as
declare @sql varchar(8000)

if @tbname like '%.%.%' --如果指定了表名,则直接导出单个表
begin
set @sql='bcp '+@tbname
+case when @isout=1 then ' out ' else ' in ' end
+' "'+@filename+'" /w'
+' /S '+@servername
+case when isnull(@username,'')='' then '' else ' /U '+@username end
+' /P '+isnull(@password,'')
exec master..xp_cmdshell @sql
end
else
begin--导出整个数据库,定义游标,取出所有的用户表
declare @m_tbname varchar(250)
if right(@filename,1)<>'/' set @filename=@filename+'/'

set @m_tbname='declare #tb cursor for select name from '+@tbname+'..sysobjects where xtype=''U'''
exec(@m_tbname)
open #tb
fetch next from #tb into @m_tbname
while @@fetch_status=0
begin
set @sql='bcp '+@tbname+'..'+@m_tbname
+case when @isout=1 then ' out ' else ' in ' end
+' "'+@filename+@m_tbname+'.txt " /w'
+' /S '+@servername
+case when isnull(@username,'')='' then '' else ' /U '+@username end
+' /P '+isnull(@password,'')
exec master..xp_cmdshell @sql
fetch next from #tb into @m_tbname
end
close #tb
deallocate #tb
end
go



精简checkbox全选代码
-----------------------------------
<script language="javascript">
function CheckAll(form)
  {
  for (var i=0;i<form.elements.length;i++)
    {
    var e = form.elements[i];
    if (e.Name != "chkAll"&&e.disabled==false)
       e.checked = form.chkAll.checked;
    }
}
</script>
<form method="post" action="" name="myform">
<input type='checkbox' name="ID1" id="ID" value='1'><br />
<input type='checkbox' name="ID2" id="ID" value='1'><br />
<input type='checkbox' name="ID2" id="ID" value='1'><br />
<input name="chkAll" type="checkbox" id="chkAll" οnclick="CheckAll(myform)" value="checkbox"> 全部选中
</form>




ADO连接数据库字符串大全

This page contains sample ADO connection strings for ODBC DSN / DSN-Less,
OLE DB Providers, Remote Data Services (RDS), MS Remote, MS DataShape.

Also included are ADO.NET connection strings for each .NET Managed Provider
(SQLClient, OLEDB, and ODBC).

These sample connection strings are compiled
by Carl Prothman, a Microsoft Visual Basic MVP
Enjoy!

 
Table of Contents
ODBC DSN Connections DSN
File DSN


ODBC DSN-Less Connections  ODBC Driver for AS/400
ODBC Driver for Access
ODBC Driver for dBASE
ODBC Driver for Excel
ODBC Driver for MySQL
ODBC Driver for oracle
ODBC Driver for Paradox
ODBC Driver for SQL Server
ODBC Driver for Sybase
ODBC Driver for Sybase SQL Anywhere
ODBC Driver for Text
ODBC Driver for Teradata
ODBC Driver for Visual FoxPro


OLE DB Data Link Connections Data Link File (UDL)


OLE DB Data Provider Connections  OLE DB Provider for AS/400
OLE DB Provider for Active Directory Service
OLE DB Provider for DB2
OLD DB Provider for Internet Publishing
OLE DB Provider for Index Server
OLE DB Provider for Microsoft Jet
OLE DB Provider for ODBC Databases
OLE DB Provider for oracle (From Microsoft)
OLE DB Provider for oracle (From oracle)
OLE DB Provider for Simple Provider
OLE DB Provider for SQL Server


Remote Data Service (RDS) Connections RDS Data Control - Connect Property
RDS Data Control - URL Property


ADO URL Connections ADO Recordset


MS Remote Provider Connections MS Remote - Access (Jet)
MS Remote - SQL Server


Data Shape Provider Connections  MS DataShape - SQL Server


.NET Managed Provider Connections SQL Client .NET Managed Provider (System.Data.SqlClient)
OLE DB .NET Managed Provider (System.Data.OleDb)
ODBC .NET Managed Provider (System.Data.ODBC)


 


ODBC DSN Connections
Using an ODBC DSN (Data Source Name) is a two step process.

1) You must first create the DSN via the "ODBC Data Source Administrator" program
found in your computer's Control Panel (or Administrative Tools menu in Windows 2000).
Make sure to create a SYSTEM DSN (not a USER DSN) when using ASP.
Note: You can also create the DSN via VB code.

2) Then use the following connection string - with your own DSN name of course.  ;-)

ODBC - DSN
 
oConn.Open "DSN=AdvWorks;" & _
          "Uid=Admin;" & _
          "Pwd=;


You can also create and use a File DSN. Then use the following ADO Connection string:

ODBC - File DSN
 
oConn.Open "FILEDSN=c:/somepath/mydb.dsn;" & _
          "Uid=Admin;" & _
          "Pwd=;"

For more information, see: About ODBC data sources and
How to Use File DSNs and DSN-less Connections

Note: The problem with DSN is that Users can (and will) modify them (or delete by mistake),
then your program won't work so well... So it's better to use a DSN-Less or OLE DB Provider
connection string with a Trusted Connection if possible!

 

ODBC DSN-Less Connections
ODBC Driver for AS/400
 
oConn.Open "Driver={Client Access ODBC Driver (32-bit)};" & _
          "System=myAS400;" & _
          "Uid=myUsername;" & _
          "Pwd=myPassword;"

For more information, see:  A Fast Path to AS/400 Client/Server

 

ODBC Driver for Access
 
For Standard Security:

oConn.Open "Driver={Microsoft Access Driver (*.mdb)};" & _
          "Dbq=c:/somepath/mydb.mdb;" & _
          "Uid=Admin;" & _
          "Pwd=;"

If you are using a Workgroup (System database):

oConn.Open "Driver={Microsoft Access Driver (*.mdb)};" & _
          "Dbq=c:/somepath/mydb.mdb;" & _
          "SystemDB=c:/somepath/mydb.mdw;", _
          "admin", ""

If MDB is located on a network share:

oConn.Open "Driver={Microsoft Access Driver (*.mdb)};" & _
          "Dbq=//myServer/myShare/myPath/myDb.mdb;"

For more information, see: Microsoft Access Driver Programming Considerations

 

ODBC Driver for dBASE
 
oConn.Open "Driver={Microsoft dBASE Driver (*.dbf)};" & _
         "DriverID=277;" & _
         "Dbq=c:/somepath;"

Note: Specify the filename in the SQL statement. For example:
     ors.Open "Select * From user.dbf", oConn, , ,adCmdText

Note: MDAC 2.1 (or greater) requires the Borland Database Engine (BDE) to update dBase DBF files. (Q238431).

For more information, see: dBASE Driver Programming Considerations

 

ODBC Driver for Excel
 
oConn.Open "Driver={Microsoft Excel Driver (*.xls)};" & _
          "DriverId=790;" & _
          "Dbq=c:/somepath/mySpreadsheet.xls;" & _
          "DefaultDir=c:/somepath;"

For more information, see: Microsoft Excel Driver Programming Considerations

 

ODBC Driver for MySQL (via MyODBC)
 
To connect to a local database

oConn.Open "Driver={mySQL};" & _
          "Server=MyServerName;" & _
          "Option=16834;" & _
          "Database=mydb;"

To connect to a remote database

oConn.Open "Driver={mySQL};" & _
          "Server=db1.database.com;" & _
          "Port=3306;" & _
          "Option=131072;" & _
          "Stmt=;" & _
          "Database=mydb;" & _
          "Uid=myUsername;" & _
          "Pwd=myPassword;"

For more information, see: Programs Known to Work with MyODBC



ODBC Driver for oracle
 
For the current oracle ODBC Driver from Microsoft:

oConn.Open "Driver={Microsoft ODBC for oracle};" & _
          "Server=OracleServer.world;" & _
          "Uid=myUsername;" & _
          "Pwd=myPassword;"

For the older oracle ODBC Driver from Microsoft:

oConn.Open "Driver={Microsoft ODBC Driver for oracle};" & _
          "ConnectString=OracleServer.world;" & _
          "Uid=myUsername;" & _
          "Pwd=myPassword;"

For more information, see: Connection String Format and Attributes

 

ODBC Driver for Paradox
 
oConn.Open "Driver={Microsoft Paradox Driver (*.db)};" & _
          "DriverID=538;" & _
          "Fil=Paradox 5.X;" & _
          "DefaultDir=c:/dbpath/;" & _
          "Dbq=c:/dbpath/;" & _
          "CollatingSequence=ASCII;"

Note: MDAC 2.1 (or greater) requires the Borland Database Engine (BDE) to update Paradox ISAM fDBF files. (Q230126).

For more information, see: Paradox Driver Programming Considerations

 

ODBC Driver for SQL Server
 
For Standard Security:

oConn.Open "Driver={SQL Server};" & _
          "Server=MyServerName;" & _
         "Database=myDatabaseName;" & _
         "Uid=myUsername;" & _
          "Pwd=myPassword;"

For Trusted Connection security:

oConn.Open "Driver={SQL Server};" & _
          "Server=MyServerName;" & _
          "Database=myDatabaseName;" & _
          "Uid=;" & _
          "Pwd=;"

' or

oConn.Open "Driver={SQL Server};" & _
          "Server=MyServerName;" & _
          "Database=myDatabaseName;" & _
          "Trusted_Connection=yes;"

To Prompt user for username and password

oConn.Properties("Prompt") = adPromptAlways
oConn.Open "Driver={SQL Server};" & _
          "Server=MyServerName;" & _
          "DataBase=myDatabaseName;"
  

For more information, see: SQLDriverConnect (ODBC)

 

ODBC Driver for Sybase
 
If using the Sybase System 11 ODBC Driver:

oConn.Open "Driver={SYBASE SYSTEM 11};" & _
          "Srvr=myServerName;" & _
         "Uid=myUsername;" & _
          "Pwd=myPassword;"

If using the Intersolv 3.10 Sybase ODBC Driver:

oConn.Open "Driver={INTERSOLV 3.10 32-BIT Sybase};" & _
          "Srvr=myServerName;" & _
         "Uid=myUsername;" & _
          "Pwd=myPassword;"

For more information, see: Sybase System 10 ODBC Driver Reference Guide

 

ODBC Driver for Sybase SQL Anywhere
 
oConn.Open "ODBC; Driver=Sybase SQL Anywhere 5.0;" & _
          "DefaultDir=c:/dbpath/;" & _
          "Dbf=c:/sqlany50/mydb.db;" & _
         "Uid=myUsername;" & _
          "Pwd=myPassword;"
          "Dsn="""";"

Note: Including the DSN tag with a null string is absolutely critical or else you get the dreaded -7778 error.

For more information, see: Sybase SQL Anywhere User Guide

 

ODBC Driver for Teradata
 
oConn.Open "Provider=Teradata;" & _
          "DBCName=MyDbcName;" & _
          "Database=MyDatabaseName;" & _
          "Uid=myUsername;" & _
          "Pwd=myPassword;"

For more information, see Teradata ODBC Driver

 

ODBC Driver for Text
 
oConn.Open "Driver={Microsoft Text Driver (*.txt; *.csv)};" & _
          "Dbq=c:/somepath/;" & _
          "Extensions=asc,csv,tab,txt;" & _
          "Persist Security Info=False"

Note: Specify the filename in the SQL statement. For example:

oRs.Open "Select * From customer.csv", _
        oConn, adOpenStatic, adLockReadOnly, adCmdText


For more information, see: Text File Driver Programming Considerations

'=================================================
'函数名:JoinChar
'作  用:自动判断链接地址并向地址中加入 ? 或 &
'参  数:strUrl  ----网址
'返回值:加了 ? 或 & 的网址
'=================================================
function JoinChar(strUrl)
 if strUrl="" then
  JoinChar=""
  exit function
 end if
 if InStr(strUrl,"?")<len(strUrl) then
  if InStr(strUrl,"?")>1 then
   if InStr(strUrl,"&")<len(strUrl) then
    JoinChar=strUrl & "&"
   else
    JoinChar=strUrl
   end if
  else
   JoinChar=strUrl & "?"
  end if
 else
  JoinChar=strUrl
 end if
end function


ODBC Driver for Visual FoxPro
 
With a database container:

oConn.Open "Driver={Microsoft Visual FoxPro Driver};" & _
          "SourceType=DBC;" & _
          "SourceDB=c:/somepath/mySourceDb.dbc;" & _
          "Exclusive=No;"

Without a database container (Free Table Directory):

oConn.Open "Driver={Microsoft Visual FoxPro Driver};" & _
          "SourceType=DBF;" & _
          "SourceDB=c:/somepath/mySourceDbFolder;" & _
          "Exclusive=No;"


For more information, see: Visual FoxPro ODBC Driver and Q165492

 


OLE DB Data Link Connections
Data Link File (UDL)
 
For Absolute Path:

oConn.Open "File Name=c:/somepath/myDatabaseName.udl;"

For Relative Path:

oConn.Open "File Name=myDatabaseName.udl;"
 

For more information, see: HOWTO: Use Data Link Files with ADO

Note: Windows 2000 no longer contains the "New | Microsoft Data Link" menu 
anymore. You can add the Data Link menu back in the menu list by running the
"C:/Program Files/Common Files/System/Ole DB/newudl.reg" reg file,
then right-click on the desktop and select "New | Microsoft Data Link" menu. 
Or you can also create a Data Link file by creating a text file and change it's
file extension to ".udl", then double-click the file.

 


OLE DB Provider Connections
OLE DB Provider for AS/400
 
oConn.Open "Provider=IBMDA400;" & _
          "Data source=myAS400;"
          "User Id=myUsername;" & _
          "Password=myPassword;"

For more information, see:  A Fast Path to AS/400 Client/Server

 

OLE DB Provider for Active Directory Service
 
oConn.Open "Provider=ADSDSOObject;" & _
          "User Id=myUsername;" & _
          "Password=myPassword;"
 

For more information, see: Microsoft OLE DB Provider for Microsoft Active Directory Service

 

OLE DB Provider for DB2
 
oConn.Open = "Provider=DB2OLEDB;" &
           "Network Transport Library=TCPIP;" &
           "Network Address=MyServer;" & _
           "Package Collection=MyPackage;" &
           "Host CCSID=1142"
           "Initial Catalog=MyDB;" &
           "User ID=MyUsername;" & _
           "Password=MyPassword;"

For more information, see: OLE DB Provider for DB2
and INF: Configuring Data Sources for the Microsoft OLE DB Provider for DB2

 

OLE DB Provider for Index Server
 
oConn.Open "Provider=msidxs;" & _
          "Data source=MyCatalog;"
 

For more information, see: Microsoft OLE DB Provider for Microsoft Indexing Service

 

OLE DB Provider for Internet Publishing
 
oConn.Open "Provider=MSDAIPP.DSO;" & _
      "Data Source=http://mywebsite/myDir;" & _
      "User Id=myUsername;" & _
      "Password=myPassword;"
 

For more information, see: Microsoft OLE DB Provider for Internet Publishing and Q245359

 

OLE DB Provider for Microsoft Jet
 
For standard security:

oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=c:/somepath/myDb.mdb;" & _
          "User Id=admin;" & _
          "Password=;"

If using a Workgroup (System Database):

oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=c:/somepath/mydb.mdb;" & _
          "Jet OLEDB:System Database=MySystem.mdw;", _
          "admin", ""

Note, remember to convert both the MDB and the MDW to the 4.0 database format when using the 4.0 OLE DB Provider.

If MDB has a database password:

oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=c:/somepath/mydb.mdb;" & _
          "Jet OLEDB:Database Password=MyDbPassword;", _
          "admin", ""

If MDB is located on a network share:

oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=//myServer/myShare/myPath/myDb.mdb;

If want to open up the Access database exclusively:

oConn.Mode = adModeShareExclusive
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=c:/somepath/myDb.mdb;" & _
          "User Id=admin;" & _
          "Password=;"


For more information, see: OLE DB Provider for Microsoft Jet, Q191754, Q225048, Q239114, and Q271908

 

You can also open an Excel Spreadsheet using the "OLE DB Provider for Microsoft Jet"

oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=c:/somepath/myExcelSpreadsheet.xls;" & _
          "Extended Properties=""Excel 8.0;HDR=Yes;"";"

Where "HDR=Yes" means that there is a header row in the cell range
(or named range), so the provider will not include the first row of the
selection into the recordset. If "HDR=No", then the provider will include
the first row of the cell range (or named ranged) into the recordset.

For more information, see: Q278973


You can also open a Text File using the "OLE DB Provider for Microsoft Jet"

oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=c:/somepath/;" & _
          "Extended Properties=""text;HDR=Yes;FMT=Delimited;"";"

' Then open a recordset based on a select on the actual file
oRs.Open "Select * From MyTextFile.txt", oConn, adOpenStatic, adLockReadOnly, adCmdText

For more information, see: Q262537

 

OLE DB Provider for ODBC Databases
 
For Access (Jet):

oConn.Open "Provider=MSDASQL;" & _
          "Driver={Microsoft Access Driver (*.mdb)};" & _
          "Dbq=c:/somepath/mydb.mdb;" & _
          "Uid=myUsername;" & _
          "Pwd=myPassword;"


For SQL Server:

oConn.Open "Provider=MSDASQL;" & _
          "Driver={SQL Server};" & _
          "Server=myServerName;" & _
          "Database=myDatabaseName;" & _
          "Uid=myUsername;" & _
          "Pwd=myPassword;"

For more information, see: Microsoft OLE DB Provider for ODBC

 

OLE DB Provider for oracle (from Microsoft)
 
oConn.Open "Provider=msdaora;" & _
          "Data Source=MyOracleDB;" & _
          "User Id=myUsername;" & _
          "Password=myPassword;"

For more information, see: Microsoft OLE DB Provider for oracle

 

OLE DB Provider for oracle (from oracle)
 
For Standard Security:

oConn.Open "Provider=OraOLEDB.Oracle;" & _
          "Data Source=MyOracleDB;" & _
          "User Id=myUsername;" & _
          "Password=myPassword;"

For a Trusted Connection:

oConn.Open "Provider=OraOLEDB.Oracle;" & _
          "Data Source=MyOracleDB;" & _
          "User Id=/;" & _
          "Password=;"
' or

oConn.Open "Provider=OraOLEDB.Oracle;" & _
          "Data Source=MyOracleDB;" & _
          "OSAuthent=1;"
 

Note: "Data Source=" must be set to the appropriate Net8 name which is known to the naming method in use. For example, for Local Naming, it is the alias in the tnsnames.ora file; for oracle Names, it is the Net8 Service Name.

For more information, see: Connecting to an oracle Database
(Note, if you get a Logon dialog, then click Cancel, then perform a one-time free signup with oracle's TechNet system)




OLE DB Provider for Simple Provider
 
The Microsoft OLE DB Simple Provider (OSP) allows ADO to access any data for which a provider has
been written using the OLE DB Simple Provider Toolkit. Simple providers are intended to access data
sources that require only fundamental OLE DB support, such as in-memory arrays or XML documents.

OSP in MDAC 2.6 has been enhanced to support opening hierarchical ADO Recordsets over arbitrary
XML files. These XML files may contain the ADO XML persistence schema, but it is not required. This
has been implemented by connecting the OSP to the MSXML2.DLL, therefore MSXML2.DLL or newer is
required.

oConn.Open "Provider=MSDAOSP;" & _
          "Data Source=MSXML2.DSOControl.2.6;"

oRS.Open "http://WebServer/VirtualRoot/MyXMLFile.xml", oConn


For more information, see: Microsoft OLE DB Simple Provider

 

OLE DB Provider for SQL Server
 
For Standard Security:

oConn.Open "Provider=sqloledb;" & _
          "Data Source=myServerName;" & _
          "Initial Catalog=myDatabaseName;" & _
          "User Id=myUsername;" & _
          "Password=myPassword;"

For a Trusted Connection:

oConn.Open "Provider=sqloledb;" & _
          "Data Source=myServerName;" & _
          "Initial Catalog=myDatabaseName;" & _
          "Integrated Security=SSPI;"

To connect to a "Named Instance" (SQL Server 2000)

oConn.Open "Provider=sqloledb;" & _
          "Data Source=myServerName/Inst2;" & _
          "Initial Catalog=myDatabaseName;" & _
          "User Id=myUsername;" & _
          "Password=myPassword;"

To Prompt user for username and password:

oConn.Provider = "sqloledb"
oConn.Properties("Prompt") = adPromptAlways
oConn.Open "Data Source=myServerName;" & _
          "Initial Catalog=myDatabaseName;"

To connect via an IP address:

oConn.Open "Provider=sqloledb;" & _
          "Data Source=xxx.xxx.xxx.xxx,1433;" & _
          "Network Library=DBMSSOCN;" & _
          "Initial Catalog=myDatabaseName;" & _
          "User ID=myUsername;" & _
          "Password=myPassword;"

Note:
- xxx.xxx.xxx.xxx is an IP address
- "Network Library=DBMSSOCN" tells OLE DB to use TCP/IP rather than Named Pipes (Q238949)
- 1433 is the default port number for SQL Server
- You can also add "Encrypt=yes" for encryption

For more information, see: Microsoft OLE DB Provider for SQL Server

Remote Data Service (RDS) Connections
The following examples show how to connect to a remote database using the RDS Data Control.
When using the RDS DataControl's Server/SQL/Connect properties, the RDS DataControl uses the
RDS DataFactory on the remote server. If you use the RDS DataControl's URL property,
then the RDS DataFactory is not used at all.

WARNING: The RDS DataFactory can be a major security hole if not setup and configured correctly!
For more information, see RDS FAQ #24

RDS DataControl - Connect Property
 
With the RDS default handler disabled (not recommend due to security risks):

With ordc
  .Server = "http://carl2"
  .Sql = "Select * From Authors Where State = 'CA'"
  .Connect = "Provider=sqloledb;" & _
           "Data Source=(local);" & _
           "Initial Catalog=pubs;" & _
           "User Id=sa;" & _
           "Password=;"
  .Refresh
End With

With the RDS default handler enabled (recommend):

With ordc
  .Server = "http://carl2"
  .Handler = "MSDFMAP.Handler"
  .Connect = "Data Source=MyConnectTag;"
  .Sql = "MySQLTag(""CA"")"
  .Refresh
End With

The corresponding CONNECT and SQL sections in the default handler /WINNT/MSDFMAP.INI file would be:

[connect MyConnectTag]
Access = ReadWrite
Connect = "Provider=sqloledb;Data Source=(local);Initial Catalog=pubs;User Id=sa;Password=;"

[sql MySQLTag]
Sql = "Select * From Authors Where State = '?'"

For more information about the RDS Default Handler, see:
Q243245, Q230680, and RDS Customization Handler Microsoft articles


RDS DataControl - URL Property
 
To get records from a remote database:

With ordc
  .URL = "http://carlp0/Authors_GetByState.asp?state=CA"
  .Refresh
End With

To save, set the URL property to an ASP web page:

With ordc
  .URL = "http://carlp0/rdsdatacontrol/Authors_Save.asp"
  .SubmitChanges
End With

For more information, see: RDS URL Property

 


ADO URL Connections
ADO 2.5+ allows you to open up a Recordset based on XML returned from an ASP file over HTTP. 
This feature doesn't use RDS at all.

ADO Recordset
 
To get records from a remote database:

oRs.Open "http://carlp0/Authors_GetByState.asp?state=CA", , _
                      adOpenStatic, adLockBatchOptimistic

To save changes, you must use the MSXML's XMLHTTP object to POST back the updated XML. 
The Recordset's Update and UpdateBatch methods will not work in this case.

' Save Recordset into Stream
Set oStm = New ADODB.Stream
oRs.Save oStm, adPersistXML

' Use MSXML's XMLHTTP object to open ASP and post a XML stream
Set oXMLHTTP = New MSXML2.XMLHTTP30
oXMLHTTP.Open "POST", "http://carlp0/Authors_Save.asp", False
oXMLHTTP.Send oStm.ReadText

' If an error occurred
If oXMLHTTP.Status = 500 Then
  Debug.Print oXMLHTTP.statusText
End If

For more information, see: ADO Recordset's Open Method

 


MS Remote Provider Connections
The following connections strings use Microsoft's remote provider (MS Remote). The MS Remote
provider tells ADO to communicate with the remote server (via the RDS DataFactory) and to use
the remote provider that is installed on the remote server.

WARNING: The RDS DataFactory can be a major security hole if not setup and configured correctly! 
For more information, see RDS FAQ #24
  

MS Remote - Access (Jet)
 
If you want to use an ODBC DSN on the remote machine:

oConn.Open "Provider=MS Remote;" & _
          "Remote Server=http://myServerName;" & _
          "Remote Provider=MSDASQL;" & _
          "DSN=AdvWorks;" & _
          "Uid=myUsername;" & _
          "Pwd=myPassword;"

If you want to use an OLE DB Provider on the remote machine:

oConn.Open "Provider=MS Remote;" & _
          "Remote Server=http://myServerName;" & _
          "Remote Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=c:/somepath/mydb.mdb;", _
          "admin", ""

If you want to use an OLE DB Provider on the remote machine (via RDS DataFactory Default Handler):

oConn.Open "Provider=MS Remote;" & _
          "Remote Server=http://myServerName;" & _
          "Handler=MSDFMAP.Handler;" & _
          "Data Source=MyAdvworksConn;"

The corresponding entry in the /winnt/Msdfmap.ini file would be:

[connect MyAdvworksConn]
Access = ReadWrite
Connect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=mydb.mdb;" & _
        "User Id=admin;" & _
        "Password=;"
 





MS Remote - SQL Server
 
If you want to use an ODBC DSN on the remote machine:

oConn.Open "Provider=MS Remote;" & _
          "Remote Server=http://myServerName;" & _
          "Remote Provider=MSDASQL;" & _
          "DSN=myDatabaseName;" & _
          "Uid=myUsername;" & _
          "Pwd=myPassword;"

If you want to use an OLE DB Provider on the remote machine:

oConn.Open "Provider=MS Remote;" & _
          "Remote Server=http://myServerName;" & _
          "Remote Provider=SQLOLEDB;" & _
         "Data Source=myServerName;" & _
         "Initial Catalog=myDatabaseName;" & _
         "User ID=myUsername;" & _
          "Password=myPassword;"

If you want to use an OLE DB Provider on the remote machine (via RDS DataFactory Default Handler):

oConn.Open "Provider=MS Remote;" & _
          "Remote Server=http://myServerName;" & _
          "Handler=MSDFMAP.Handler;" & _
          "Data Source=MyPubsConn;"

The corresponding entry in the /winnt/Msdfmap.ini file would be:

[connect MyPubsConn]
Access = ReadWrite
Connect = "Provider=SQLOLEDB;" & _
        "Data Source=myServerName;" & _
        "Initial Catalog=myDatabaseName;" & _
        "User ID=myUsername;" & _
        "Password=myPassword;"

For more information, see: Microsoft OLE DB Remoting Provider  and Q240838

 


Data Shape Provider Connections
MS DataShape - SQL Server
 
oConn.Open "Provider=MSDataShape;" & _
          "Data Provider=SQLOLEDB;" & _
          "Data Source=mySQLServerName;" & _
          "Initial Catalog=myDatabase;" & _
          "User ID=myUsername;" & _
          "Password=myPassword;"

Then use a Shape command with SQL strings:
sSQL = "SHAPE {select * from authors} " & _
      "APPEND ({select * from titleauthor} AS chapter " & _
      "RELATE au_id TO au_id)"

Or use a Shape command that calls Stored Procedures:
sSQL = "SHAPE {exec spAuthors_LoadAll} " & _
      "APPEND ({exec spTitleAuthor_LoadAll} AS chapter " & _
      "RELATE au_id TO au_id)"

For more information, see: Microsoft Data Shaping Service for OLE DB and Q288409

 


.NET Managed Provider Connections
SQL Client .NET Managed Provider (System.Data.SqlClient)
 
The SQL Client .NET Managed Provide allows you to connect to a Microsoft SQL Server 7.0
or 2000 database. For Microsoft SQL Server 6.0 or earlier, use the OLE DB .NET Data Provider
with the "SQL Server OLE DB Provider" (SQLOLEDB).

Dim oSQLConnection As SqlClient.SqlConnection
Dim sConnString As String

sConnString = "Data Source=(local);" & _
           "Initial Catalog=NorthWind;" & _
           "Integrated Security=SSPI;" & _
           "Pooling=True;" & _
           "Min Pool Size=10;" & _
           "Max Pool Size=50;" & _
           "Connection Lifetime=30;" & _
           "Connection Reset=True;" & _
           "Enlist=True;"
oSQLConnection = New SqlClient.SqlConnection(sConnString)
oSQLConnection.Open()

For more information, see: System.Data.SQL Namespace and .NET Data Providers
Note: 'SQL' namespace got renamed to 'SQLClient'

 

OLE DB .NET Managed Provider (System.Data.OleDb)
 
The OLE DB .NET Data Provider uses native OLE DB through COM interop to enable data access. 
To use the OLE DB .NET Data Provider, you must also use an OLE DB provider (e.g. SQLOLEDB,
MSDAORA, or Microsoft.JET.OLEDB.4.0).

For SQL Server OLE DB Provider (for SQL Server 6.0 or earlier)

Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String

sConnString = "Provider=sqloledb;" & _
           "Data Source=myServerName;" & _
           "Initial Catalog=myDatabaseName;" & _
           "User Id=myUsername;" & _
          "Password=myPassword;"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()

For JET OLE DB Provider:

Dim oOleDbConnection As OleDb.OleDbConnection
Dim sConnString As String

sConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
           "Data Source=C:/Work/nwind.mdb;" & _
           "User ID=Admin;" & _
           "Password="";"
oOleDbConnection = New OleDb.OleDbConnection(sConnString)
oOleDbConnection.Open()

For more information, see: System.Data.OleDb Namespace and .NET Data Providers
Note: 'ADO' namespace got renamed to 'OleDb'

 

ODBC .NET Managed Provider (System.Data.ODBC)
 
The ODBC .NET Data Provider is an add-on component to the .NET Framework SDK Beta 2.
It provides access to native ODBC drivers the same way the OLE DB .NET Data Provider
provides access to native OLE DB providers.

For SQL Server ODBC Driver:

Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String

' Create and open a new ODBC Connection
sConnString = "Driver={SQL Server};" & _
           "Server=MySQLServerName;" & _
           "Database=MyDatabaseName;" & _
           "Uid=MyUsername;" & _
           "Pwd=MyPassword;"

oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()

For oracle ODBC Driver:

Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String

' Create and open a new ODBC Connection
sConnString = "Driver={Microsoft ODBC for oracle};" & _
          "Server=OracleServer.world;" & _
          "Uid=myUsername;" & _
          "Pwd=myPassword;"

oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()

For Access (JET) ODBC Driver:

Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String

' Create and open a new ODBC Connection
sConnString = "Driver={Microsoft Access Driver (*.mdb)};" & _
          "Dbq=c:/somepath/mydb.mdb;" & _
          "Uid=Admin;" & _
          "Pwd=;"

oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()

For all other ODBC Drivers:

Dim oODBCConnection As Odbc.OdbcConnection
Dim sConnString As String

' Create and open a new ODBC Connection
sConnString = "Dsn=myDsn;" & _
           "Uid=myUsername;" & _
           "Pwd=myPassword;"

oODBCConnection = New Odbc.OdbcConnection(sConnString)
oODBCConnection.Open()

  • 0
    点赞
  • 0
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值