Runoob Tutorial ArchiveEnglish

ADO Update Log

ADO Update Log


We can use SQL's UPDATE to update a record in a database table.


Update a record in a database table

We want to update a record in the Customers table of the Northwind data. First, we need to create a table to list all records in Customers.

<%

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

%>

List Database

<%

for each x in rs.Fields

  response.write("

next

%>

<% do until rs.EOF %>

<%

for each x in rs.Fields

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

  

  <%else%>

    

<%end if

next

%>

<%rs.MoveNext%>

<%

loop

conn.close

%>

")
" & ucase(x.name) & "

    

    

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

If the user clicks the button in the "customerID" column, a new file "demo_update.asp" will open. This file contains the source code for creating input fields, which are based on the fields recorded in the database, and also includes an "Update" button to save the changes:

Update Record

<%

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

%>

  

  

<%for each x in rs.Fields%>

  

  

  

<%next%>

  

  

<%=x.name%>

  

  

  

<%

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

conn.close

%>