第一步,我们要建立一个名为db_sample.mdb的数据库(本文以Access2000数据库为例),并在其中建立表T_Sample.表T_Sample包括如下字段:
ID 自动编号
U_Name 文本
U_Info 备注
第二步,我们开始设计搜索页面Search.asp.该页面包括一个表单(Frm_Search),表单内包括一个文本框和一个提交按钮。并将表单的method属性设为“get” ,action属性设为“Search.asp",即提交给网页自身。代码如下:
<!-- Search.asp --> <form name="frm_Search" method="get" action="Search.asp"> 请输入关键字: <input type="text" name="key" size="10"> <input type="submit" value="搜索"> </form> |
<% Dim strProvider,CNN strProvider="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" strProvider=strProvider & Server.MapPath("/") & "/data/db_Sample.mdb" ’假设数据库存放在主页根目录下的data目录下 Set CNN = Server.CreateObject("ADODB.connection") CNN.Open strProvider 打开数据库连接 %> |
<font color="#FF0000">未找到任何结果!!!</font> <% Else %> |
<% While Not RST.EOF 遍历整个记录集,显示搜索到的信息并设置链接 %> <!-- 此处可设为你所需要的链接目标 --> <font style="font: 12pt 宋体"><a href="info.asp?ID=<%= RST("ID") %>" target="_blank"><%= RST("U_Name") %></a></font> <!-- 显示部分详细内容 --> <font style="font: 9pt 宋体"><%= Left(RST("U_Info"),150) %></font><p> <% RST.MoveNext Wend RST.Close Set RST=Nothing End If End If %> |
<% Function AutoKey(strKey) CONST lngSubKey=2 Dim lngLenKey, strNew1, strNew2, i, strSubKey ’检测字符串的合法性,若不合法则转到出错页。出错页你可以根据需要进行设定。 if InStr(strKey,"=")<>0 or InStr(strKey,"`")<>0 or InStr(strKey,"")<>0 or InStr(strKey," ")<>0 or InStr(strKey," ")<>0 or InStr(strKey,"")<>0 or InStr(strKey,chr(34))<>0 or InStr(strKey,"/")<>0 or InStr(strKey,",")<>0 or InStr(strKey,"<")<>0 or InStr(strKey,">")<>0 then Response.Redirect "error.htm" End If lngLenKey=Len(strKey) Select Case lngLenKey Case 0 ’若为空串,转到出错页 Response.Redirect "error.htm" Case 1 ’若长度为1,则不设任何值 strNew1="" strNew2="" ’Case Else 若长度大于1,则从字符串首字符开始,循环取长度为2的子字符串作为查询条件 For i=1 To lngLenKey-(lngSubKey-1) strSubKey=Mid(strKey,i,lngSubKey) strNew1=strNew1 & " or U_Name like %" & strSubKey & "%" strNew2=strNew2 & " or U_Info like %" & strSubKey & "%" Next End Select ’得到完整的SQL语句 AutoKey="Select * from T_Sample where U_Name like %" & strKey & "% or U_Info like %" & strKey & "%" & strNew1 & strNew2 End Function %> |
<% CNN.Close Set CNN=Nothing %> |