天天看點

ADO 更新記錄

我們可使用 SQL 的 UPDATE 來更新資料庫表中的某條記錄。 

我們希望更新 Northwind 資料中 Customers 表的某條記錄。首先我們需要建立一個表格,來列出 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>List Database</h2>

<table border="1" width="100%">

<tr>

for each x in rs.Fields

  response.write("<th>" & ucase(x.name) & "</th>")

next

</tr>

<% do until rs.EOF %>

<form method="post" action="demo_update.asp">

  if lcase(x.name)="customerid" then%>

    <td>

    <input type="submit" name="customerID" value="<%=x.value%>">

    </td>

  <%else%>

    <td><%Response.Write(x.value)%></td>

  <%end if

</form>

<%rs.MoveNext%>

loop

conn.close

</table>

</body>

</html>

如果使用者點選 "customerID" 列中的按鈕,會打開一個新檔案 "demo_update.asp"。此檔案包含了建立輸入域的源代碼,這些輸入域基于資料庫中記錄的字段,同時也含有一個儲存修改的"更新按鈕":

<h2>Update Record</h2>

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_update.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="Update record">

  </form>

else

  sql="UPDATE customers SET "

  sql=sql & "companyname='" & Request.Form("companyname") & "',"

  sql=sql & "contactname='" & Request.Form("contactname") & "',"

  sql=sql & "address='" & Request.Form("address") & "',"

  sql=sql & "city='" & Request.Form("city") & "',"

  sql=sql & "postalcode='" & Request.Form("postalcode") & "',"

  sql=sql & "country='" & Request.Form("country") & "'"

  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 updated!")

  end if

end if