Xóa ghi ADO

Chúng ta có thể sử dụng lệnh DELETE của SQL để xóa một bản ghi nào đó trong bảng cơ sở dữ liệu.

Xóa bản ghi trong bảng

Chúng tôi hy vọng xóa một bản ghi trong bảng Customers của cơ sở dữ liệu Northwind. Trước hết, chúng tôi cần tạo một bảng để liệt kê tất cả các bản ghi trong Customers.

<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers",conn
%>
<h2>Danh sách cơ sở dữ liệu</h2>
<table border="1" width="100%">
<tr>
<%
for each x in rs.Fields
  response.write("<th>" & ucase(x.name) & "</th>")
tiếp theo
%>
</tr>
<% do until rs.EOF %>
<tr>
<form method="post" action="demo_delete.asp">
<%
for each x in rs.Fields
  if x.name="customerID" then%>
    <td>
    <input type="submit" name="customerID" value="<%=x.value%>">
    </td>
  <%else%>
    <td><%Response.Write(x.value)%></td>
  <%end if
tiếp theo
%>
</form>
<%rs.MoveNext%>
</tr>
<%
lặp lại
conn.close
%>
</table>
</body>
</html>

Nếu người dùng nhấn nút trong cột "customerID", sẽ mở tệp mới "demo_delete.asp". Tệp này chứa mã nguồn tạo trường nhập dựa trên các trường của bản ghi trong cơ sở dữ liệu, đồng thời cũng chứa nút "Xóa ghi" để xóa bản ghi hiện tại:

<html>
<body>
<h2>Xóa ghi</h2>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
cid=Request.Form("customerID"
if Request.form("companyname")="" then
  set rs=Server.CreateObject("ADODB.Recordset")
  rs.open "SELECT * FROM customers WHERE customerID='" & cid & "'",conn
  %>
  <form method="post" action="demo_delete.asp">
  <table>
  <%for each x in rs.Fields%>
  <tr>
  <td><%=x.name%></td>
  <td><input name="<%=x.name%>" value="<%=x.value%>"></td>
  <%next%>
  </tr>
  </table>
  <br /><br />
  <input type="submit" value="Delete record">
  </form>
<%
else
  sql="DELETE FROM customers"
  sql=sql & " WHERE customerID='" & cid & "'"
  on error resume next
  conn.Execute sql
  if err<>0 then
    response.write("No update permissions!")
  else 
    response.write("Record " & cid & " was deleted!")
  end if 
end if
conn.close
%>
</body>
</html>