Add record to ADO
Add record to ADO
We can add records to a table in the database using the SQL INSERT INTO command.
Add a record to a table in the database
We want to add a new record to the Customers table in the Northwind database. First, we need to create a form that contains the input fields from which we need to collect data:
When the user clicks the confirm button, this form will be submitted to the file named "demo_add.asp". The file "demo_add.asp" contains code to add a new record to the Customers table:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
sql="INSERT INTO customers (customerID,companyname,"
sql=sql & "contactname,address,city,postalcode,country)"
sql=sql & " VALUES "
sql=sql & "('" & Request.Form("custid") & "',"
sql=sql & "'" & Request.Form("compname") & "',"
sql=sql & "'" & Request.Form("contname") & "',"
sql=sql & "'" & Request.Form("address") & "',"
sql=sql & "'" & Request.Form("city") & "',"
sql=sql & "'" & Request.Form("postcode") & "',"
sql=sql & "'" & Request.Form("country") & "')"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else
Response.Write("
" & recaffected & " record added
")end if
conn.close
%>
Important Notes
When using the INSERT command, please note the following:
- If the table has a primary key, ensure that the value added to the primary key field is unique and not null (otherwise, the provider will not append this record, or an error may occur).
- If the table has an auto-increment field, do not include this field in the INSERT statement (the value of this field is managed by the provider).
Regarding fields with no data.
In an MS Access database, if you set the AllowZeroLength property to "Yes", you can enter zero-length strings ("") in text, hyperlink, and memo fields.
**Note:** Not all databases support zero-length strings, so errors may occur when adding records with empty fields. Therefore, it is important to check the data types supported by the database you are using.