ADO 删除记录

我们可使用 SQL 的 DELETE 命令来删除数据库表中的某条记录。

删除表中的记录

我们希望删除 Northwind 数据库的 Customers 表中的一条记录。首先我们需要创建一个表格,来列出 Customers 中的所有记录。

  1. <html>
  2. <body>
  3. <%
  4. set conn=Server.CreateObject("ADODB.Connection")
  5. conn.Provider="Microsoft.Jet.OLEDB.4.0"
  6. conn.Open "c:/webdata/northwind.mdb"
  7. set rs=Server.CreateObject("ADODB.Recordset")
  8. rs.open "SELECT * FROM customers",conn
  9. %>
  10.  
  11. <h2>List Database</h2>
  12. <table border="1" width="100%">
  13. <tr>
  14. <%
  15. for each x in rs.Fields
  16. response.write("<th>" & ucase(x.name) & "</th>")
  17. next
  18. %>
  19. </tr>
  20. <% do until rs.EOF %>
  21. <tr>
  22. <form method="post" action="demo_delete.asp">
  23. <%
  24. for each x in rs.Fields
  25. if x.name="customerID" then%>
  26. <td>
  27. <input type="submit" name="customerID" value="<%=x.value%>">
  28. </td>
  29. <%else%>
  30. <td><%Response.Write(x.value)%></td>
  31. <%end if
  32. next
  33. %>
  34. </form>
  35. <%rs.MoveNext%>
  36. </tr>
  37. <%
  38. loop
  39. conn.close
  40. %>
  41. </table>
  42.  
  43. </body>
  44. </html>

假如用户点击 "customerID" 列中的按钮,会打开新文件 "demo_delete.asp"。此文件包含了创建输入域的源代码,这些输入域基于数据库中记录的字段,同时也含有一个删除当前记录的“删除按钮”:

  1. <html>
  2. <body>
  3.  
  4. <h2>Delete Record</h2>
  5. <%
  6. set conn=Server.CreateObject("ADODB.Connection")
  7. conn.Provider="Microsoft.Jet.OLEDB.4.0"
  8. conn.Open "c:/webdata/northwind.mdb"
  9.  
  10. cid=Request.Form("customerID"
  11.  
  12. if Request.form("companyname")="" then
  13. set rs=Server.CreateObject("ADODB.Recordset")
  14. rs.open "SELECT * FROM customers WHERE customerID='" & cid & "'",conn
  15. %>
  16. <form method="post" action="demo_delete.asp">
  17. <table>
  18. <%for each x in rs.Fields%>
  19. <tr>
  20. <td><%=x.name%></td>
  21. <td><input name="<%=x.name%>" value="<%=x.value%>"></td>
  22. <%next%>
  23. </tr>
  24. </table>
  25. <br /><br />
  26. <input type="submit" value="Delete record">
  27. </form>
  28. <%
  29. else
  30. sql="DELETE FROM customers"
  31. sql=sql & " WHERE customerID='" & cid & "'"
  32. on error resume next
  33. conn.Execute sql
  34. if err<>0 then
  35. response.write("No update permissions!")
  36. else
  37. response.write("Record " & cid & " was deleted!")
  38. end if
  39. end if
  40. conn.close
  41. %>
  42.  
  43. </body>
  44. </html>